0

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)
                })
            }
        })
ShaneN
  • 7
  • 8
  • Are your outlets wired up? Is the little circle next to `@IBOutlet usernameField` filled in? If it is hollow, drag from that circle to usernamefield in your Storyboard. – vacawama Jan 24 '16 at 14:49
  • Possible duplicate of [Fatal error: unexpectedly found nil while unwrapping an Optional values](http://stackoverflow.com/questions/24643522/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-values) – GoZoner Jan 24 '16 at 15:16

1 Answers1

0

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

MikeG
  • 3,006
  • 1
  • 24
  • 48