Use of local variable 'displayAlert' before its declaration - ios

I have called function and It isn't still displaying the code right I have been receiving and error Use of local variable 'displayAlert' before its declaration
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
// I have also switched the #IBAction to function so the code actually run better any suggestions to fix this
#IBOutlet weak var dropoffLabel: UILabel!
#IBOutlet weak var pickupLabel: UILabel!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var emailTextfield: UITextField!
#IBOutlet weak var pickupDropoffSwitch: UISwitch!
#IBOutlet weak var buttomButton: UIButton!
#IBOutlet weak var topButton: UIButton!
var signUpMode = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func topTapped(_ sender: Any) {
if emailTextfield.text == "" || passwordTextField.text == "" {
code error coming from here ----> displayAlert(title: "Missing Information", message: "You must provide both a email and password")
} else {
if let email = emailTextfield.text {
if let password = passwordTextField.text {
if signUpMode {
// SIGN UP
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
displayAlert(title: "Error", message: error!.localizedDescription)
} else {
print("Sign Up Success")
}
})
} else {
// LOG IN
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
displayAlert(title: "Error", message: error!.localizedDescription)
} else {
print("Sign Up Success")
}
})
}
}
}
}
------> I believe if I am doing it correctly called the function here func displayAlert(title:String, message:String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
//there is no other issue besides the code not understanding the the function I have labeled
//Also I have ran the code before and the alert would pop up but now it is not allowing the
func buttomTapped(_ sender: Any) {
if signUpMode {
topButton.setTitle("Log In", for: .normal)
buttomButton.setTitle("Switch to Sign Up", for: .normal)
pickupLabel.isHidden = true
dropoffLabel.isHidden = true
pickupDropoffSwitch.isHidden = true
signUpMode = false
} else {
topButton.setTitle("Sign Up", for: .normal)
buttomButton.setTitle("Switch to Log In", for: .normal)
pickupLabel.isHidden = false
dropoffLabel.isHidden = false
pickupDropoffSwitch.isHidden = false
signUpMode = true
}
}
}
}

You have incorrectly defined your displayAlert func inside the topTapped func.
You need to move it outside so it is on the class level
#IBAction func topTapped(_ sender: Any) {
//code here
}
func displayAlert(title:String, message:String) {
//
}

Related

Merge user info email/phone number authentication, Firebase firestore with swift

Create a user with Username, email, and password. Then force the user to complete phone number verification before the account is created.
I am designing an app where we would like to make the user sign up by creating a username, password, supply their email address, and then complete phone number verification.
This picture represents the desired flow we would like our user to complete to register their account.
here are our View Controller files:
This is the code for the "Create Account" view, it creates a user in Firebase using email
import UIKit
class CreateAccountVC: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var usernameTextfield: UITextField!
#IBOutlet weak var passwordTextfield: UITextField!
#IBOutlet weak var emailTextfield: UITextField!
#IBOutlet weak var confirmPasswordTextfield: UITextField!
#IBOutlet weak var createAccountLbl: UILabel!
#IBOutlet weak var createAccountTextView: UILabel!
#IBOutlet weak var signupBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil)
overrideUserInterfaceStyle = .light
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
signupBtn.clipsToBounds = true
signupBtn.layer.cornerRadius = 15
signupBtn.addButtonGradient(didType: true)
}
#objc func keyboardWillShow(notification:NSNotification){
let userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
scrollView.contentInset = contentInset
}
#objc func keyboardWillHide(notification:NSNotification){
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInset
}
#IBAction func alreadyHaveAccountBtnPressed(_ sender: Any) {
// dismiss(animated: true, completion: nil)
// self.performSegue(withIdentifier: "TypePhoneNumberVC", sender: self)
}
#IBAction func signupBtnPressed(_ sender: Any) {
let username = usernameTextfield.text
let email = emailTextfield.text
let password = passwordTextfield.text
signupBtn.isHidden = true
AuthorizationService.instance.registerUser(username: username!, email: email!, password: password!) { (success, err) in
if success{
AuthorizationService.instance.loginUser(withEmail: email!, andPassword: password!) { (success, err) in
if err != nil{
return
}
self.performSegue(withIdentifier: "EnterNumberSegue", sender: self)
print("Sign-up successful")
}
}else{
let alertController = UIAlertController(title: "Error", message: err?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
self.signupBtn.isHidden = false
}
}
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
These next two demonstrate the implementation of the Phone number verification
import UIKit
import Firebase
import FirebaseAuth
class EnterPhoneNumberVC: UIViewController, UITextFieldDelegate{
#IBOutlet weak var backButton: UIButton!
#IBOutlet weak var phoneNumberUITextField: UITextField!
#IBOutlet weak var getCodeButton: UIButton!
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
phoneNumberUITextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(handle))
view.addGestureRecognizer(tap)
overrideUserInterfaceStyle = .light
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getCodeButton.clipsToBounds = true
getCodeButton.layer.cornerRadius = 15
getCodeButton.addButtonGradient(didType: true)
}
#objc func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
#IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func getCodeButtonPressed(_ sender: Any) {
guard let phoneNumber = phoneNumberUITextField.text else {return}
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
if error == nil {
print(verificationID)
guard let verifyID = verificationID else {return}
self.userDefaults.set(verifyID, forKey:"verificationID")
self.userDefaults.synchronize()
self.performSegue(withIdentifier: "GetCodeSegue", sender: self)
} else {
print("unable to confirm the users phone number", error?.localizedDescription)
}
}
}
import UIKit
import Firebase
import FirebaseAuth
class PhoneNumberVerificationVC: UIViewController, UITextFieldDelegate {
#IBOutlet weak var verifyBtn: UIButton!
#IBOutlet weak var resendCodeBtn: UIButton!
#IBOutlet weak var otpCode: UITextField!
var verificationID: String?
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
let tap = UITapGestureRecognizer(target: self, action: #selector(handle))
view.addGestureRecognizer(tap)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
verifyBtn.clipsToBounds = true
verifyBtn.layer.cornerRadius = 15
verifyBtn.addButtonGradient(didType: true)
}
#objc func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func verifyBtnPressed(_ sender: Any) {
guard let optCode = otpCode.text else {return}
guard let verificationID = userDefaults.string(forKey: "verificationID") else {return}
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: optCode)
Auth.auth().signInAndRetrieveData(with: credential) { (success, error) in
if error == nil {
print(success)
self.performSegue(withIdentifier: "VerifiedSegue", sender: self)
print("The user has successfully logged In and is verified!")
} else {
print("Error: Phone number and One time password does not match")
}
}
}

fatal error: unexpectedly found nil while unwrapping an Optional value Parse sign up

I'm trying to do a signup page but for some reason I keep getting the same error "fatal error: unexpectedly found nil while unwrapping an Optional value" on the line "let username = self.usernameField.text" when I test it out in the simulator. I know the error has something to do with a value being nil but cant figure out how to fix it please help :(
Code =
#IBOutlet weak var emailField: UITextField?
#IBOutlet weak var usernameField: UITextField?
#IBOutlet weak var passwordField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signUpAction(sender: AnyObject) {
let username = self.usernameField!.text
let password = self.passwordField!.text
let email = self.emailField!.text
let finalEmail = email!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Validate the text fields
if username?.characters.count < 5 {
let alert = UIAlertView(title: "Invalid", message: "Username must be greater than 5 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else if password?.characters.count < 8 {
let alert = UIAlertView(title: "Invalid", message: "Password must be greater than 8 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else if email?.characters.count < 8 {
let alert = UIAlertView(title: "Invalid", message: "Please enter a valid email address", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
spinner.startAnimating()
let newUser = PFUser()
newUser.username = username
newUser.password = password
newUser.email = finalEmail
// Sign up the user asynchronously
newUser.signUpInBackgroundWithBlock({ (succeed, error) -> Void in
// Stop the spinner
spinner.stopAnimating()
if ((error) != nil) {
let alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else {
let alert = UIAlertView(title: "Success", message: "Signed Up", delegate: self, cancelButtonTitle: "OK")
alert.show()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Home")
self.presentViewController(viewController, animated: true, completion: nil)
})
}
})
Try this...
import Foundation
import Parse
import UIKit
class LoginViewController: UIViewController {
#IBOutlet weak var userNameTF: UITextField!
#IBOutlet weak var passWordTF: UITextField!
#IBOutlet weak var emailTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func SignUp(sender: AnyObject) {
signUp()
}
#IBAction func Login(sender: AnyObject) {
login()
}
func signUp() {
let user = PFUser()
user.username = userNameTF.text
user.password = passWordTF.text
user.email = emailTF.text
// other fields can be set if you want to save more information
// user["phone"] = "650-555-0000"
user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if error == nil {
print("Sign Up Succesful")
} else {
print("Sign Up Failed")
}
}
}
func login() {
let user = PFUser()
user.username = userNameTF.text
user.password = passWordTF.text
PFUser.logInWithUsernameInBackground(userNameTF.text!, password: passWordTF.text!, block: {
(user: PFUser?, Error: NSError?) -> Void in
if Error == nil {
dispatch_async(dispatch_get_main_queue()) {
var Storyboard = UIStoryboard(name: "Main", bundle: nil)
var AfterLoginVC: UIViewController = Storyboard.instantiateViewControllerWithIdentifier("AfterLoginVC") as! UINavigationController
self.presentViewController(AfterLoginVC, animated: true, completion: nil)
}
} else {
print("Login Error, check credentials")
}
})
}
}
"AterLoginVC" is the storyboard identifier of the view controller that you want to instantiate after a successful attempt at login. From this you can then add you if/else statements to evaluate conditions and return the error to the user accordingly

codes are not dismissing keyboard

I added resignFirstResponder and touchesBegan to my code but the keyboard is not dismissing. I already checked the delegate and assigned delegate to textfields but still no sign of dismissing.
Please help spot the error? (i'm guessing it might be about multiple textFields?)
import UIKit
import Parse
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBAction func BackToFirstPageButton(sender: AnyObject) {
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
func SignOutForEmailVerification() {
PFUser.logOut()
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTextField: UITextField!
#IBOutlet var EmailTextField: UITextField!
var ActivityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
#IBAction func SignUpButton(sender: AnyObject) {
if UsernameTextField.text == "" || PasswordTextField.text == "" || EmailTextField.text == "" {
let SignUpAlert = UIAlertController (title: "Error in form", message: "Please fill in the blanks", preferredStyle: UIAlertControllerStyle.Alert)
SignUpAlert.addAction((UIAlertAction(title: "Dismiss", style: .Default, handler: { (action) -> Void in
})))
self.presentViewController(SignUpAlert, animated: true, completion: nil)
} else {
ActivityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
ActivityIndicator.center = self.view.center
ActivityIndicator.hidesWhenStopped = true
ActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(ActivityIndicator)
ActivityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
user.email = EmailTextField.text
user.signUpInBackgroundWithBlock({ (success, error) -> Void in
self.ActivityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil {
let EmailVerificationAlert = UIAlertController(title: "Email Verification", message: "Please click the link in an email we have just sent you", preferredStyle: UIAlertControllerStyle.Alert)
EmailVerificationAlert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { EmailVerificationAlert in self.SignOutForEmailVerification()})
)
self.presentViewController(EmailVerificationAlert, animated: true, completion: nil)
}
})
}
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.UsernameTextField.delegate = self
self.PasswordTextField.delegate = self
self.EmailTextField.delegate = self
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
}
}
When user taps "Return" key on the keyboard
As you already added the UITextFieldDelegate, try modifying this code :
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.UsernameTextField.resignFirstResponder();
self.EmailTextField.resignFirstResponder();
self.PasswordTextField.resignFirstResponder();
return true;
}
This will work when the user taps the button return on the keyboard.
Your mistake is as you said handling multiple text fields. Also you have to say which one you want to resignFirstResponder().
When user taps screen
User could also dismiss the keyboard by tapping anywhere on the screen.
Here we have a UITapGestureRecognizer that detects the tap to dismiss keyboard. It is an alternative solution.
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
import UIKit
import Parse
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTextField: UITextField!
#IBOutlet var EmailTextField: UITextField!
var ActivityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
var currentTextField : UITextField?
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.UsernameTextField.delegate = self
self.PasswordTextField.delegate = self
self.EmailTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func BackToFirstPageButton(sender: AnyObject) {
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
func SignOutForEmailVerification() {
PFUser.logOut()
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
#IBAction func SignUpButton(sender: AnyObject) {
if UsernameTextField.text == "" || PasswordTextField.text == "" || EmailTextField.text == "" {
let SignUpAlert = UIAlertController (title: "Error in form", message: "Please fill in the blanks", preferredStyle: UIAlertControllerStyle.Alert)
SignUpAlert.addAction((UIAlertAction(title: "Dismiss", style: .Default, handler: { (action) -> Void in
})))
self.presentViewController(SignUpAlert, animated: true, completion: nil)
} else {
currentTextField?.resignFirstResponder();
ActivityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
ActivityIndicator.center = self.view.center
ActivityIndicator.hidesWhenStopped = true
ActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(ActivityIndicator)
ActivityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
user.email = EmailTextField.text
user.signUpInBackgroundWithBlock({ (success, error) -> Void in
self.ActivityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil {
let EmailVerificationAlert = UIAlertController(title: "Email Verification", message: "Please click the link in an email we have just sent you", preferredStyle: UIAlertControllerStyle.Alert)
EmailVerificationAlert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { EmailVerificationAlert in self.SignOutForEmailVerification()})
)
self.presentViewController(EmailVerificationAlert, animated: true, completion: nil)
}
})
}
func textFieldDidBeginEditing(textField: UITextField!){
currentTextField = textField;
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
currentTextField.resignFirstResponder()
return true
}
}
}

Parse login issue invalid login parameters

when i try to login to Parse on ios simulator using my app id and client id it shows "invalid login parameters (Code: 101, Version: 1.8.2)" but when i tried Udemy's ios tutor's app id and client id it was worked. My code is alright and i think the problem is in Parse. Is there anybody has had an issue like this?
import UIKit
import Parse
import Bolts
class ViewController: UIViewController {
var signUp = true // for creating current mode of the page
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
// login iv outlet
#IBOutlet weak var signUpB: UIButton!
#IBOutlet weak var loginB: UIButton!
#IBOutlet weak var registerText: UILabel!
var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView() // for spinner
//for displaying alert
func displayAlert(title:String,message:String){
var alert = UIAlertController(title:title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "ok", style: .Default , handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}
#IBAction func signUp(sender: AnyObject) {
if username.text == "" || password.text == "" {
displayAlert("Error in form", message: "Please enter username and password")
}
else {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var errorMessage = "Please try again later"
if signUp == true
{
var user = PFUser()
user.username = username.text
user.password = username.text
user.signUpInBackgroundWithBlock(
{(success, error) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil
{
// sign up successful
}
else {
if let errorString = error!.userInfo?["error"] as? String
{
errorMessage = errorString
}
self.displayAlert("Failed ", message: errorMessage)
}
})
} else {
PFUser.logInWithUsernameInBackground(username.text, password: password.text, block:
{ (user, error) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if user != nil
{
// logged in
}
else {
if let errorString = error!.userInfo?["error"] as? String
{
errorMessage = errorString
}
self.displayAlert("Failed Login", message: errorMessage)
}
})
}
}
}
#IBAction func login(sender: AnyObject) {
if signUp == true {
signUpB.setTitle("Login", forState: UIControlState.Normal)
registerText.text = "Not Registered?"
loginB.setTitle("Sign Up", forState: UIControlState.Normal)
signUp = false
}
else{
signUpB.setTitle("Sign Up", forState: UIControlState.Normal)
registerText.text = "Already Registered?"
loginB.setTitle("Login", forState: UIControlState.Normal)
signUp = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I got the same error "invalid login parameter" and I know why.
The problem is the response message itself from Parse, it makes us confused.
"Invalid login parameter" means "Wrong username or password".
Just enter the right username and password and it's done!
I had exactly this problem, two things I did:
in AppDelegate I commented out
// PFUser.enableRevocableSessionInBackground()
more here: Parse invalid session token error 1.8.2
2 In your login viewController (after updating to new Facebook SDK) I added the following:
import ParseFacebookUtilsV4

Core Data How would I use core data to keep the user logged in?

I am making this app called imagur and it has a signup and login and whenever I leave the app when the user already has an account I want it to automatically recognize the user how would I do that this is what I have so far :
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var signupActive = true
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
func displayAlert(title:String, error:String) {
var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
#IBOutlet var username: UITextField!
#IBOutlet var password: UITextField!
#IBOutlet var alreadyRegistered: UILabel!
#IBOutlet var signUpButton: UIButton!
#IBOutlet var signUpLabel: UILabel!
#IBOutlet var signUpToggleButton: UIButton!
#IBAction func toggleSignUp(sender: AnyObject) {
if signupActive == true {
signupActive = false
signUpLabel.text = "Use the form below to log in"
signUpButton.setTitle("Log In", forState: UIControlState.Normal)
alreadyRegistered.text = "Not Registered?"
signUpToggleButton.setTitle("Sign Up", forState: UIControlState.Normal)
} else {
signupActive = true
signUpLabel.text = "Use the form below to sign up"
signUpButton.setTitle("Sign Up", forState: UIControlState.Normal)
alreadyRegistered.text = "Already Registered?"
signUpToggleButton.setTitle("Log In", forState: UIControlState.Normal)
}
}
#IBAction func signUp(sender: AnyObject) {
var error = ""
if username.text == "" || password.text == "" {
error = "Please enter a username and password"
}
if error != "" {
displayAlert("Error In Form", error: error)
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
if signupActive == true {
var user = PFUser()
user.username = username.text
user.password = password.text
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, signupError: NSError!) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if signupError == nil {
// Hooray! Let them use the app now.
println("signed up")
} else {
if let errorString = signupError.userInfo?["error"] as? NSString {
error = errorString
} else {
error = "Please try again later."
}
self.displayAlert("Could Not Sign Up", error: error)
}
}
} else {
PFUser.logInWithUsernameInBackground(username.text, password:password.text) {
(user: PFUser!, signupError: NSError!) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if signupError == nil {
println("logged in")
} else {
if let errorString = signupError.userInfo?["error"] as? NSString {
error = errorString
} else {
error = "Please try again later."
}
self.displayAlert("Could Not Log In", error: error)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Oh and I am also using Parse.
If all you are wanting to do is remember that a user is logged in across app closures/reboots, then you can simply save that fact with NSUserDefaults and check NSUserDefaults at launch. This is a pretty straightforward approach.
Using core data just to persist if a user is logged in is probably overkill.
If you are actually needing to remember their user name and password, then that is another question entirely. You should not user Core Data or NSUserDefaults in this scenario. To securely store user credentials you'll want to use the Keychain Service in the security framework.

Resources