I am trying to print text into a text field like this:
How to do that the right way?
else {
weak var worgnlogin: UILabel! {
worgnlogin.text = ("brugernavn eller password er skrevet forkert")
}
}
Here you have my main ViewController code I have made an array with all users infomation, as I will loop through and get the right user to login:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtUserName: UITextField!
#IBOutlet weak var txtPassword: UITextField!
#IBOutlet weak var worgLogin: UILabel!
let user1 = ["user": "Karsten","userID":"1","userName":"Kalle","passWord":"1234" ]
let user2 = ["user": "Rene","userID":"2","userName":"Rene" ,"passWord":"1234" ]
let user3 = ["user": "Johan","userID":"3","userName":"Johan","passWord":"1234" ]
override func viewDidLoad() {
super.viewDidLoad()
let array = [user1,user2,user3]
UserDefaults.standard.set(array, forKey: "users")
// Do any additional setup after loading the view, typically from a nib.
if UserDefaults.standard.bool(forKey: "ISUSERLOGGEDIN") == true {
//user is already logged in just navigate him to home screen
let homeVc = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
self.navigationController?.pushViewController(homeVc, animated: false)
}
}
#IBAction func authenticateUser(_ sender: Any) {
if txtUserName.text == "userName" && txtPassword.text == "passWord" {
//navigate to home screen
UserDefaults.standard.set(true, forKey: "ISUSERLOGGEDIN")
let homeVc = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
self.navigationController?.pushViewController(homeVc, animated: true)
}else {
displayMyAlertMessage(userMessage: "Brugernavn eller Password er skrevet forkert");
return;
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertController.Style.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertAction.Style.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}
i hobe this make a better understanding :)
worgnlogin.text = "brugernavn eller password er skrevet forkert"
First create an IBOutlet for a label:
#IBOutlet weak var worgnLoginLabel: UILabel!
Then in your else statement write:
self.worgnLoginLabel.text = “your message”
Related
I have this code and when I am running the App on the line with "super.viewDidLoad()", I have the "Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee0234ff0" error...
Can someone help me please?
On internet they say me that I have to connect my Developer Account, but I don't have one.
This is the code :
import Foundation
import UIKit
import FirebaseAuth
import FirebaseDatabase
class SignUpController : UIViewController {
//Fonction pour scroller
private let scrollView: UIScrollView = {
let scrollView = UIScrollView.self()
scrollView.clipsToBounds = true
return scrollView
}()
//MARK : Outlets
#IBOutlet weak var artistnameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var confirmationPasswordTextField: UITextField!
#IBOutlet weak var signupButton: UIButton!
#IBOutlet weak var loginButton: UIButton!
//MARK : Properties
override func viewDidLoad() {
super.viewDidLoad()
viewDidLoad()
//Add subviews
view.addSubview(scrollView)
scrollView.addSubview(artistnameTextField)
scrollView.addSubview(emailTextField)
scrollView.addSubview(passwordTextField)
scrollView.addSubview(confirmationPasswordTextField)
scrollView.addSubview(signupButton)
scrollView.addSubview(loginButton)
//Design
setupButtons()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showLogin" {
let VCDestination = segue.destination as! LoginController
VCDestination.myMail = emailTextField.text!
}
if segue.identifier == "showLogin" {
let VCDestination = segue.destination as! LoginController
VCDestination.myPassword = passwordTextField.text!
}
}
//MARK : Private Methods
private func setupButtons() {
signupButton.layer.cornerRadius = 20
loginButton.layer.cornerRadius = 20
loginButton.layer.borderWidth = 3
loginButton.layer.borderColor = UIColor.lightGray.cgColor
}
private func setupTextFieldManager() {
artistnameTextField.delegate = self
emailTextField.delegate = self
passwordTextField.delegate = self
let tapGesture = UITapGestureRecognizer (target: self, action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
//MARK : Actions
#IBAction func signUpButton(_ sender: UIButton) {
performSegue(withIdentifier: "showLogin", sender: nil)
}
#objc private func hideKeyboard() {
artistnameTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
}
#IBAction func signupButtonWasPressed(_ sender: UIButton) {
if artistnameTextField !== "" as AnyObject && emailTextField !== "" as AnyObject && passwordTextField !== "" as AnyObject && confirmationPasswordTextField.text == passwordTextField.text {
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (authResult, error) in
if error != nil {
print(error.debugDescription)
self.alertUserLoginError()
} else {
print ("Inscription en cours...")
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).setValue(["artistName": self.artistnameTextField.text])
self.performSegue(withIdentifier: "goToHome", sender: self)
}
}
} else {
print("Veuillez remplir tous les champs.")
}
}
#IBAction func loginButtonWasPressed(_ sender: UIButton) {
print("Redirection vers l'écran de connexion...")
}
func alertUserLoginError() {
let alert = UIAlertController(title: "Erreur", message: "Veuillez remplir tous les champs", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
present(alert, animated: true)
}
}
extension SignUpController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
Thanks
Ok so for the sake of brevity, here's a concept called "App Lifecycle" which by its nature is the methods that are called by the iOS system and in a specific order. Remember that computers can only run one thing at a time, per CPU. So it must go in an order of some sort. The iOS lifecycle events are as follows.
loadView()
viewDidLoad()
viewWillAppear()
viewDidAppear()
didReceiveMemoryWarning()
viewWillDisappear()
viewDidDisappear()
Now bear in mind there are a few others depending on what you're doing but these are the most common ones.
With 90% of these lifecycle methods, there's something more that is going on in the background that you don't see. This is where the super.methodName() call comes into play. It allows you to add additional functionality at a given lifecycle event without losing any of the other functionality that is being provided by that method. Otherwise, you might lose something that is required to load the view. Eg, super.methodName retains all previous functionality.
Now, to your issue, you have the following lines of code.
override func viewDidLoad() {
super.viewDidLoad()
viewDidLoad()
//A bunch more code after this.
}
Looking at the Lifecycle methods, that are required in many cases, notice that you are calling viewDidLoad() inside of your super.viewDidLoad which means that your main thread gets stuck. It loops back through that method that called it, and then there it is again, another viewDidLoad() call. In turn, it loops, again, and again, and again, until it crashes. There is a time and a place for recursion, however, this is not one of them, and that's for a completely separate topic.
Ultimately your solution is to remove the viewDidLoad() method call after your super.viewDidLoad() and that will resolve the error that you're having.
I'm running into an error when transitioning to view controllers by overriding the built-in prepare() function in Swift. I have a UIImageView for backgrounds on my screens. Here is the code for two of the view controllers in question.
import UIKit
import FirebaseAuth
class HomeVC: UIViewController {
#IBOutlet weak var signOutButton: UIButton!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendsNavButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var profileNavButton: UIButton!
#IBOutlet weak var bumpButton: UIButton!
#IBOutlet weak var welcomeLabel: UILabel!
#IBOutlet weak var doNotDisturbLabel: UILabel!
#IBOutlet weak var doNotDisturbButton: UIButton!
var userName = ""
var dndIsOn: Bool = false
#IBAction func dndToggled(_ sender: Any) {
dndIsOn = !dndIsOn
User.current.available = !dndIsOn
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).updateData([Constants.Firestore.Keys.available : !dndIsOn])
if dndIsOn {
print("DND is on!")
setupDNDUI()
} else if !dndIsOn {
print("DND is off!")
setupActiveUI()
}
}
#IBAction func signOutTapped(_ sender: Any) {
let firAuth = Auth.auth()
do {
try firAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
print("Successfully signed out")
}
#IBAction func bumpTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toCall, sender: self)
}
#IBAction func friendsNavTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toFriends, sender: self)
}
#IBAction func profileNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(ProfileVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
doNotDisturbLabel.isHidden = true
if !userName.isEmpty {
welcomeLabel.text = "Welcome Back, " + userName + "!"
} else {
welcomeLabel.text = ""
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let friendsVC = segue.destination as? FriendsVC else {
return
}
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).getDocument { (snapshot, err) in
if let err = err {
print(err.localizedDescription)
} else {
let data = snapshot!.data()!
let requests = data[Constants.Firestore.Keys.requests] as? [String]
if let requests = requests {
friendsVC.requests = requests
}
}
}
}
class FriendsVC: UIViewController {
//var friends: [Friend] = User.current.friends
var friends: [User] = []
var requests: [String]?
#IBOutlet weak var requestsNumberLabel: UILabel!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendRequestsButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var friendsTitle: UILabel!
#IBOutlet weak var friendTableView: UITableView!
#IBOutlet weak var addFriendButton: UIButton!
#IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
#IBAction func friendRequestsTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toRequests, sender: self)
}
#IBAction func homeNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(HomeVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
friendTableView.backgroundView?.backgroundColor = .white
friendsTitle.isHidden = false
UserService.getUserArray(uids: User.current.friendUids, completion: { (users) in
guard let users = users else {
print("User has no friends")
return
}
self.friends = users
self.friendTableView.reloadData()
})
guard let requests = self.requests else {
friendRequestsButton.isHidden = true
requestsNumberLabel.isHidden = true
self.tableViewTopConstraint.constant = 0
return
}
requestsNumberLabel.text = requests.count.description
// Do any additional setup after loading the view.
friendTableView.delegate = self
friendTableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let homeVC = segue.destination as? HomeVC {
homeVC.userName = User.current.firstName
} else if let requestsVC = segue.destination as? RequestsVC {
UserService.getUserArray(uids: self.requests!) { (requesters) in
if let requesters = requesters {
requestsVC.requesters = requesters
}
}
}
}
}
When my app loads into the home screen, there is no problem, and when a button is tapped to transition to FriendsVC, there is no problem. However, when I try to initiate the transition from HomeVC to ProfileVC or from FriendVC to HomeVC, I get the error: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" at the self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill lines in my viewDidLoad methods. These segues have something in common in that these are the ones where I override the prepare() function, but I'm not sure what I'm doing wrong
Every time, when I use a Facebook account to log in the application is supposed to have identified email shows up on the Firebase console but it doesn’t work properly. Users can use their Facebook account to access the application, but the problem is my profile page always got a crash when I attempt to make that page shows email of the users up. but if I use an email account to log in it doesn’t have any problem the email that I used to sign up able to shows up normally.
I have done everything in this link but can’t fix this problem.
https://firebase.google.com/docs/auth/ios/facebook-login
On the profile page, I use this code to call the email and user
import UIKit
import Firebase
import FirebaseAuth
import FacebookLogin
import FacebookCore
import FirebaseStorage
class ProfileViewController: UIViewController {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var emailLabel: UILabel!
#IBOutlet weak var passTextField: UITextField!
#IBOutlet weak var changeNameText: UITextField!
#IBOutlet weak var menuButton: UIBarButtonItem!
#IBOutlet weak var imageProfile: UIImageView!
#IBOutlet weak var alertButton: UIBarButtonItem!
let imageUniqueName = UUID().uuidString
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
let user = Auth.auth().currentUser
setUserDataToView(withFIRUser: user!)
customizeNavBar()
sideMenus()
let tapGesture = UITapGestureRecognizer()
tapGesture.addTarget(self, action: #selector(ProfileViewController.openGallery(tapGesture:)))
imageProfile.isUserInteractionEnabled = true
imageProfile.addGestureRecognizer(tapGesture)
imageProfile.drawAsCircle()
}
func setUserDataToView(withFIRUser user: User) {
nameLabel.text = user.displayName
emailLabel.text = "อีเมล์ : \(user.email!)"
}
this is all code on my LoginViewController page
import UIKit
import Firebase
import FirebaseAuth
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKCoreKit
import FacebookLogin
import FacebookCore
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print("โปรดตรวจสอบใหม่อีกรอบ", error.localizedDescription)
} else if result.isCancelled {
} else {
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
ProgressHUD.showSuccess("ยินดีต้อนรับ")
self.performSegue(withIdentifier: "Main", sender: self)
}
}
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
ProgressHUD.showSuccess("ออกจากระบบสำเร็จ")
}
let loginButton = FBSDKLoginButton()
//Textfields pre-linked with IBOutlets
#IBOutlet var emailTextfield: UITextField!
#IBOutlet var passwordTextfield: UITextField!
#IBOutlet weak var facebookButton: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
loginButton.delegate = self
loginButton.readPermissions = ["public_profile", "email"]
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func logInPressed(_ sender: AnyObject) {
//TODO: Log in the user
Auth.auth().signIn(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
if error != nil{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
print(error!)
}else{
ProgressHUD.showSuccess("ยินดีต้อนรับ")
self.performSegue(withIdentifier: "Main", sender: self)
}
}
}
#IBAction func onClickPassword(_ sender: Any) {
if self.passwordTextfield.isSecureTextEntry == true {
self.passwordTextfield.isSecureTextEntry = false
}
else {
self.passwordTextfield.isSecureTextEntry = true
}
}
override func viewDidAppear(_ animated: Bool){
super.viewDidAppear(animated)
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "Main", sender: nil)
}
}
}
enter image description here
I'm new to Swift. I'm in process of making a shopping list app. There are two UITextField, one for the item name and the other for the item quantity that saves to the dictionary. I would like to share this list with UIActivityViewController, but it only shares the last value. Can someone advice me how to share all item and amount with the UIActivityViewController.
var shoppinglist = [String:String]()
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Amount: UITextField!
#IBAction func Add(_ sender: UIButton) {
var item = Item.text!
var amount = Amount.text!
shoppinglist [item] = amount
print(shoppinglist)
}
#IBAction func share(_ sender: UIButton) {
let activityController = UIActivityViewController(activityItems: [shoppinglist], applicationActivities: nil)
present(activityController,animated: true,completion: nil)
}
}
Try following code. I hope this coding helps for you.
class shoppinglist:NSObject {
var yourItem:String = ""
var amount:Int = 0
init(yourItem:String, amount:Int) {
self.yourItem = yourItem
self.amount = amount
}
}
Declare the variables inside your class
var shoppingListArray = [shoppinglist]()
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Amount: UITextField!
#IBAction func Add(_ sender: UIButton) {
self.shoppingListArray.append(shoppinglist(yourItem:Item.text, amount:Int(Amount.text!)!))
print(shoppingListArray)
}
#IBAction func share(_ sender: UIButton) {
let activityController = UIActivityViewController(activityItems: shoppingListArray, applicationActivities: nil)
present(activityController,animated: true,completion: nil)
}
}
try this:-
#IBAction func share(_ sender: UIButton) {
let activityVc = UIActivityViewController(activityItems: ["here your item name","item quantity"], applicationActivities:nil)
activityVc.popoverPresentationController?.sourceView = self.view
self.present(activityVc, animated:true, completion:nil)
}
I am currently trying to write the users information to firebase's database after using the create user function FIRAuth.auth()?.createUser
Under this function I attempt to insert the data into the database like this:
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in
if error == nil
{
let email = self.emailField.text
let firstName = self.firstnameField.text
let lastName = self.lastnameField.text
self.ref.child((user?.uid)!).setValue(["firstName": firstName,"lastName": lastName,"email": email])
self.performSegue(withIdentifier: "createaccountLandingPage", sender: sender)
}
It also may be important to mention that under my view controller I create the reference to the database using:
var ref = FIRDatabase.database().reference().child("users") //root database
My outlets are all correct, but I am getting this error:
Thread 1: signal SIGABRT
Any suggestions on what I may be doing incorrectly?
EDIT** Here is all my code in the signup view controller
import UIKit
import Firebase
import FirebaseDatabase
class CreateAccountViewController: UIViewController {
var ref = FIRDatabase.database().reference().child("users") //root database
#IBOutlet weak var firstnameField: UITextField!
#IBOutlet weak var lastnameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmpasswordField: UITextField!
#IBOutlet weak var createAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if (FIRAuth.auth()?.currentUser) != nil
{
}
else
{
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func createAccountAction(_ sender: AnyObject)
{
if self.confirmpasswordField.text != self.passwordField.text
{
}
else
{
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in
if error == nil
{
let user = FIRAuth.auth()?.currentUser.uid
let email = self.emailField.text
let firstName = self.firstnameField.text
let lastName = self.lastnameField.text
self.ref.child("users").child("\(user)").setValue(["firstName": firstName,"lastName": lastName,"email": email])
self.performSegue(withIdentifier: "createaccountLandingPage", sender: sender)
}
else
{
let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
EDIT*** here is a screenshot of the error
EDIT**** here is a screenshot of my podfile and when it is updated I recieve no errors in the terminal.
EDIT***** Screenshots of console.
1stScreenshotConsole
2ndScreenshotConsole
You have to create a reference to your database like this
Var ref: FIRDatabaseReference!
Then you initialize your database in your viewDidLoad like this
Ref = FIRDatabase.database().reference()
I wrote the whole code below, excuse the syntax errors because I am answering your question on an iPad.
import UIKit
import Firebase
import FirebaseDatabase
class CreateAccountViewController: UIViewController {
var ref = FIRDatabaseReference! //create a reference for your database
#IBOutlet weak var firstnameField: UITextField!
#IBOutlet weak var lastnameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmpasswordField: UITextField!
#IBOutlet weak var createAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//initialize your database
ref = FIRDatabase.database().reference()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func createAccountAction(_ sender: AnyObject)
{
if self.confirmpasswordField.text != self.passwordField.text
{
}
else
{
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in
if error == nil
{
let user = FIRAuth.auth()?.currentUser.uid //get the users UID after registering
let email = self.emailField.text
let firstName = self.firstnameField.text
let lastName = self.lastnameField.text
self.ref.child("users").child("\(user!)").setValue(["firstName": "\(firstName!)", "lastName": "\(lastName!)", "email": "\(email!)"])
self.performSegue(withIdentifier: "createaccountLandingPage", sender: sender)
}
else
{
let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}