Swift 5 - Navigation Pages - ios

I am just getting to work with Swift 5 and have to update my apps. I use....
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Home")
self.present(vc, animated: true, completion: nil)
to push users from a sign-in screen to the main app, yet with the updates here's how it looks below (iPhone currently in dark-mode)...
Some questions. What is this functionality definitively called? and how do I go about manipulating it? Say I want to remove it because right now if the user is in the main app they can swipe down and go back to the sign-in screen which would definitely cause problems.
Sign-In View Controller Code
import UIKit
import Firebase
import RealmSwift
class StartViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Check if user is already logged-in so they don't have to sign-in again
checkUserSignIn()
// Setting textfield delegates so user can press enter and go to next textfield
self.email.delegate = self
self.password.delegate = self
let uid = Auth.auth().currentUser?.uid
print(uid)
print("printing the uid here")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add a background view to the table view
let backgroundImage = UIImage(named: "startBackground")
let imageView = UIImageView(image: backgroundImage)
self.tableView.backgroundView = imageView
imageView.contentMode = .scaleAspectFill
}
// Check if user is already signed-in, if so push to main app
func checkUserSignIn() {
Auth.auth().addStateDidChangeListener({ (auth, user) in
if (user != nil) {
Database.database().reference().child("users").child((user?.uid)!).observeSingleEvent(of: .value, with: { snapshot in
if snapshot.exists() {
print("user is logged in")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Home")
vc.modalPresentationStyle = .overCurrentContext
self.present(vc, animated: true, completion: nil)
}
})
}
})
}
#IBAction func login(_ sender: Any) {
if self.email.text == "" || self.password.text == "" {
//Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().signIn(withEmail: self.email.text!, password: self.password.text!) { (user, error) in
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
// Proceed To App
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "home") {
} else {
print("Problem sending user into nature app")
}
}
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
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)
}
}
}
}
#IBAction func createAccount(_ sender: Any) {
// Check user has entered text into fields
guard let email = email.text, email != "",
let password = password.text, password != ""
else {
// Throw alert message to user if fields are empty
let alert = UIAlertController(title: "Registration Error", message: "Please make sure you filled in all of the boxes to complete registration!", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
return
}
// Register a new user on Firebase
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
// Throw registration error / Account could already exist
if let error = error {
let alert = UIAlertController(title: "Registration Error", message: error.localizedDescription, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
return
}
guard let userID = user?.user.uid else {
return
}
// Database reference
let databaseRef = Database.database().reference()
// Set user information to firebase data structure
let userInfo = fireUsersData(email: email, profPicString: "", uid: userID)
databaseRef.child("users").child(userID).updateChildValues(userInfo.getUserDictionary(), withCompletionBlock: { (err, databaseRef) in
let UserToAdd = realmUserData()
UserToAdd.email = email
UserToAdd.uid = userID
//UserToAdd.saveDataToRealm()
if err != nil {
// Throw error is problem completeting
let alert = UIAlertController(title: "Error", message: (err?.localizedDescription)! as String, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
})
})
// Dismiss keyboard
self.view.endEditing(true)
// Proceed To App
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "home") {
} else {
print("Problem sending user into nature app")
}
}
}
// END OF FILE
}

Before presenting your ViewController give this option:
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Home")
vc.modalPresentationStyle = .overCurrentContext
self.present(vc, animated: true, completion: nil)
For ignoring dark mode style in didFinishLaunchingWithOptions write this:
if #available(iOS 13.0, *) {
window?.overrideUserInterfaceStyle = .light
}
UPDATE: Replace present to this code:
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Home") as! UITabBarController
UIApplication.shared.keyWindow?.rootViewController = vc

Related

iOS issue in login screen: signupActionButton is not showing valid result

I am trying to learn swift, my "SignupButtonAction" is not redirecting to signup screen, please help. Thank you in advance
import UIKit
class Login: UIViewController {
#IBOutlet weak var emailID: UITextField!
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
// Hitting Signup screen
#IBAction func SignupButtonAction(_ sender: Any) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let Signup = mainStoryboard.instantiateViewController(withIdentifier: "Signup")
self.navigationController?.pushViewController(Signup, animated: true)
}
//Login button action
#IBAction func loginButtonAction(_ sender: Any) {
let emailID = emailID.text;
let password = password.text;
//check for empty fields
if (emailID?.isEmpty ?? true || password?.isEmpty ?? true) {
// diplay alert message
displayalert(usermessage: "All fields are required");
return;
}
// store data
UserDefaults.standard.set(emailID, forKey: "emailID");
UserDefaults.standard.set(password, forKey: "password");
// display alert message with confirmation
let myAlert = UIAlertController(title: "Alert", message: "Login successful, Thank you!", preferredStyle: UIAlertController.Style.alert);
let okAction = UIAlertAction(title: "ok", style: .default) { action in
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let dashboard = mainStoryboard.instantiateViewController(withIdentifier: "Dashboard")
self.navigationController?.pushViewController(dashboard, animated: true)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
// displaying error alert
func displayalert(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);
}
}

Adding Activity Indicator after Clicking "LOGIN"?

I would like to add an Activity Indicator for my Login VC so that users will see that spinner thing once they click the "login" button. I have done multiple attempts and failed. Even if I put in codes for hiding the activity indicator, it just keeps animating even before clicking the "login" button. I deleted those codes, and have my original codes below (without activity indicator).
import UIKit
import Firebase
class LoginViewController: UIViewController {
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.image = #imageLiteral(resourceName: "background")
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubview(toBack: imageView)
}
//Outlets
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
//Login Action
#IBAction func loginAction(_ sender: AnyObject) {
if self.emailTextField.text == "" || self.passwordTextField.text == "" {
//Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
//Go to the HomeViewController if the login is sucessful
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
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)
}
}
}
}
so I know the first step is probably dragging the activity indicator to the VC in Storyboard, but what's next?
You need to create a IBOutlet of dragged UIActivityIndicator. Then in viewDidLoadfunc hide this UIActivityIndicator with it's IBOutlet. When you click on Login Button, then unhide this activityIndicator and hide again, once receive response from login.
Create an IBOUtlet of your activity indicator from Storyboard to your Viewcontroller -
You can then in your ViewDidLoad or your storyboard set the below property
activityIndicator.hidesWhenStopped = true;
And when you want to start it, call
activityIndicator.startAnimating();
And to stop it from animating -
activityIndicator.stopAnimating();
The same way you created your IBOutlets of UITextField, create one with your UIActivityIndicator. Make sure your indicator's hidesWhenStopped is set to true in the storyboard.
Then animate it before calling your signin method, and stop it on the completion handler
#IBOutlet weak var activityIndicator: UIActivityIndicator!
//...
activityIndicator.startAnimating()
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in {
activityIndicator.stopAnimating()
//...
}
You can create UIActivityIndicatorView in your class programmatically & customize it in viewDidLoad
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
// Add below code in viewDidLoad
self.activityIndicator.hidesWhenStopped = true
self.activityIndicator.center = view.center
self.view.addSubView(self.activityIndicator)
Now do start & stop animating whereever you need
//Login Action
#IBAction func loginAction(_ sender: AnyObject) {
self.activityIndicator.startAnimating()
if self.emailTextField.text == "" || self.passwordTextField.text == "" {
//Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
self.activityIndicator.stopAnimating()
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
//Go to the HomeViewController if the login is sucessful
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
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)
}
}
}
In your storyboard, you can find checkbox.
startsAnimating
HidesWhenStops(check this in your storyboard.)
#IBOutlet weak var activityIndicator: UIActivityIndicator!
#IBAction func loginAction(_ sender: AnyObject) {
activityIndicator.startAnimating()
if self.emailTextField.text == "" || self.passwordTextField.text == "" {
//Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert)
activityIndicator.stopAnimating()
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
activityIndicator.stopAnimating()
//Go to the HomeViewController if the login is sucessful
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
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)
}
}
}
}
An alternative Approach. Adding the UIActivityViewController programatically:
In the LoginViewController class add
let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
In the viewDidLoad() add the following
myActivityIndicator.hidesWhenStopped = true
myActivityIndicator.center = view.center
view.addSubview(myActivityIndicator)
In #IBAction func loginAction(_ sender: AnyObject) in the else part
add
activityIndicator.startAnimating()
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in {
activityIndicator.stopAnimating()
I have written a class to use progress hud properly. You just need to drag and drop the class to your project...
https://github.com/emraz/ERProgressHud
For showing progress hud write ..
ERProgressHud.show()
For hiding progress hud write ..
ERProgressHud.hide()
In your code ..
//Login Action
#IBAction func loginAction(_ sender: AnyObject) {
if self.emailTextField.text == "" || self.passwordTextField.text == "" {
//Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
return
}
else {
ERProgressHud.show()
Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
ERProgressHud.hide()
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
//Go to the HomeViewController if the login is sucessful
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
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)
}
}
}
}

Data is not being inserted under the node of user UID in Firebase in Swift 3

When I save data under userID the data is not being stored into the Firebase and give error unexpectedly found nil while unwrapping an optional value, however when I use childByAutoID the data is being stored successfully. Help me to save under userID node. Here I have explained that when I create the user under signup action this is happening.
#IBAction func createAccountAction(_ sender: Any) {
if self.emailTextField.text == "" || self.passwordTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else if (self.passwordTextField.text != self.retypePasswordfield.text) {
let alertController = UIAlertController(title: "Error", message: "Password does not match", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else {
ref.child("user_registration").setValue(["username": self.fullName.text, "email": self.emailTextField.text,"contact": self.numberText.text, "city": self.myCity.text, "state": self.countryText.text, "gender": genderGroup, "blood": bloodGroup])
FIRAuth.auth()?.createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
if error == nil {
FIRAuth.auth()?.currentUser!.sendEmailVerification(completion: { (error) in
})
print("You have successfully signed up")
let alertController = UIAlertController(title: "Successful!", message: "Email Verification link sent", preferredStyle: .alert)
let alertActionOkay = UIAlertAction(title: "Okay", style: .default) { (action) in
let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginFirstViewController")
self.present(vc!, animated: true, completion: nil)
}
alertController.addAction(alertActionOkay)
self.present(alertController, animated: true, completion: nil)
} else {
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)
}
}
}
}
Only for reference
This is the current working code for me
On signUp Button
// Create new User
FIRAuth.auth()?.createUser(withEmail: self.tfEmail.text!, password: self.tfPassword.text!, completion: { (user, error) in
if error == nil{ // IF NO ERROR
let astrContact = self.strDialCode + " " + self.tfMobileNumber.text!
// Dict to add user data in firebase Db
let aDBDict : [String : String] = ["userName": self.tfFullName.text!,
"userEmail": self.tfEmail.text!,
"userContact": astrContact,
"userCountry": self.strCode,
"userID": (user?.uid)!]
// Add data in DB
ref?.child("Customer/\(String(describing: (user?.uid)!)/userProfileDetails").setValue(aDBDict)
DispatchQueue.main.async(execute: { () -> Void in
// goto home VC
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navController = storyboard.instantiateViewController(withIdentifier: "MainController")
if let window = AppDelegate.getAppDelegate().window {
window.rootViewController = navController
}
})
}
else{ // If error in creating new user
print("error in creating new user")
print(error!)
}
})
In appDelegate
extension AppDelegate {
class func getAppDelegate() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
}

Display alert in current view, and as well as Redirect to another view

I want to display alert for check new version of my app from API. And from that view if userDefault data is store so base on that I want to redirect to another view. My redirection code is work perfectly but when I add alert code so redirection doesn't work. I think alert present in "self" and that time I also try to redirect from that view so it's may create problem. Here is my code..
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateUserData() //base on userDefault redirection
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkNewVersion() //Alert function for API calling
}
func checkNewVersion() -> Void {
//TODO: For check App new version
WebRequester.shared.getAppNewVersion { (result, error) in
if result != nil {
if result?.value(forKey: "status") as! Bool {
let strVer = (result?.object(forKey: "data") as! NSDictionary).object(forKey: "platform_version") as! String
if UserData.getAppVersion() < strVer {
let alert = UIAlertController(title: "Alert", message: "New version of App available", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: { (action) in
})
let AppStore = UIAlertAction(title: "App Store", style: .default, handler: { (action) in
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1024941703"),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
}
})
alert.addAction(ok)
alert.addAction(AppStore)
self.present(alert, animated: true, completion: nil)
// OperationQueue().addOperation {
// // Put queue to the main thread which will update the UI
// OperationQueue.main.addOperation({
// self.present(alert, animated: true, completion: nil)
// })
// }
}
}
else {
if (result?.object(forKey: "data") as! NSArray).object(at: 0) as? String ?? "" == "Unauthorised access." {
Model.shared.deleteAllCoreDataRecord(entity: "CartItem")
UIApplication.topViewController()?.navigationController?.popToRootViewController(animated: true)
}
let msg = result?.value(forKey: "data") as! [String]
Model.shared.showAlert(title: "Error", msg: msg[0], controller: self)
}
}
else {
Model.shared.showAlert(title: "Error", msg: error?.localizedDescription ?? "Something went wrong at add new address", controller: self)
}
}
}
func updateUserData() -> Void {
if UserData.getAppVersion() == "1.0" {
if UserData.getUserData() != nil {
//TODO: check for user Updated data
let params = ["mobile":UserData.getUserMobile()] as [String : Any]
let propic = UIImage(named: "temp")
weak var objWeek = self
Model.shared.showActivity(WithTouchEnable: false,controller: self)
WebRequester.shared.customerSignup(params: params as NSDictionary, proImg: propic!){ (result,error) -> Void in
Model.shared.HideActivity(controller: self)
if (error == nil) {
print("login result:",result ?? "")
//handle response of sign up
let statusstr = result?["status"] as! Bool
if (statusstr == false) {
//This condition for pepsi welcome offer is expire or not
let user = result!["user_info"] as! NSDictionary
self.storeUserData(user: user)
if UserData.getUserMobileNumVerify() == "No" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let registerScreen = storyboard.instantiateViewController(withIdentifier: "UserRegisterPhoneVC") as! UserRegisterPhoneVC
objWeek?.navigationController?.pushViewController(registerScreen, animated: true)
}
else {
if UserData.getPepsiOfferRedim() == "1" || UserData.getPepsiOfferRedim() == "2" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let offerScreen = storyboard.instantiateViewController(withIdentifier: "OfferViewController") as! OfferViewController
objWeek?.navigationController?.pushViewController(offerScreen, animated: true)
}
else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let promoScreen = storyboard.instantiateViewController(withIdentifier: "PromotionViewController") as! PromotionViewController
objWeek?.navigationController?.pushViewController(promoScreen, animated: true)
}
}
}
}
}
else {
Model.shared.showAlert(title: "Error", msg: (error?.localizedDescription)!, controller: self)
}
}
}
}
}
To achieve this , you need to click on alert OK button then only it will automatically navigate to other controller , without this not possible .
Here is code :
Alert controller block help you to achieve this :
//show an alert and navigate to previous controller
let alertController: UIAlertController = UIAlertController(title: "Password updatd", message: "your alert message", preferredStyle: .alert)
let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
//Redirect to new viewcontroler
let newVC = self.storyboard.instantiateViewcontroller(identifier: "newvc") as? NewVC
self.navigationController?.pushViewController(newVC,animated: true)
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
Feel free to comment. Thanks

UIViewController failing to navigate to another page in swift

I have previously written this function and it was working fine. I started working on the project again after a week's break and the same code is not working. Am I missing something here? Basically if a button is pushed, checkCredentials will run. Everything in the "else" section is working completely fine, but the if user != nil section isn't working:
func checkCredentials (){
PFUser.logInWithUsernameInBackground(usernameLoginTxt.text!, password: passwordLoginTxt.text!){
(user:PFUser?, error:NSError?) -> Void in
if user != nil{
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("SearchViewController") as UIViewController
self.presentViewController(vc, animated: false, completion:nil)
NSLog("it was successfull dude")
}else{
let title = "Warning!"
let message = "You have entered the wrong username or password.\n Please try again!"
let okButton = "Ok"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okayButton = UIAlertAction(title: okButton, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okayButton)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
This should work for you...
func login(){
let user = PFUser()
user.username = userNameText.text
user.password = passwordText.text
PFUser.logInWithUsernameInBackground(userNameText.text!, password: passwordText.text!, block: {
(user: PFUser?, Error: NSError?) -> Void in
if Error == nil {
dispatch_async(dispatch_get_main_queue()) {
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let AfterLoginVC: UIViewController = Storyboard.instantiateViewControllerWithIdentifier("AfterLoginVC") as! UINavigationController
self.presentViewController(AfterLoginVC, animated: true, completion: nil)
}
} else {
let title = "Warning!"
let message = "You have entered the wrong username or password.\n Please try again!"
let okButton = "Ok"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okayButton = UIAlertAction(title: okButton, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(okayButton)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
Also be sure that over the last week you didn't accidentally change your Parse client key (I've done that before) which will cause it to not show any error but simply to not work.

Resources