0

昨晚它还在工作,但是当我运行我的代码时,现在我收到了:

致命错误:在展开可选值时意外发现 nil。

有人可以帮我找到这个错误吗?

import UIKit
class UserRegistration: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate {

//USER REGISTRATION FORM

//Activity Indicator
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()

//Error
func displayAlert(title:String, error:String){
    //create Alert
    var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

//User Profile Picture Selection
var profileImage = UIImage()
var isThereImage = false
@IBOutlet var uploadProfilePictureButton: UIButton!
@IBAction func uploadProfilePicture(sender: AnyObject) {
    //Settings needed for image upload
    var image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary //can use '.camera' to access camera
    image.allowsEditing = true
    //Select image. FYI Completion is a function that happens when viewcontroller is presented
    self.presentViewController(image, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!)  {
        //Store image in local variable to be resized later
        profileImage = image
        println("Image is selected")
        //Manually Close View Controller
        self.dismissViewControllerAnimated(true, completion: nil)
        //Remove button title
        uploadProfilePictureButton.setTitle("", forState: .Normal)
        //Display Image
        uploadProfilePictureButton.setBackgroundImage(image, forState: .Normal)
        //Set isThereImage Boolean
        isThereImage = true
    }

//---------------------------------------

//User Input Information
@IBOutlet var userEmailAddress: UITextField!
@IBOutlet var userPasswordOne: UITextField!
@IBOutlet var userPasswordTwo: UITextField!
@IBOutlet var passwordConfirmationMatch: UILabel!
var confirmedPassword = Bool()

//---------------------------------------

//Submit User Input to Database

@IBAction func userRegistration(sender: AnyObject) {
    var error = ""
    //Verify if User Exist and Passwords Match
    if userEmailAddress.text == "" || userPasswordOne.text == "" || confirmedPassword == false {
            error = "Please enter an email address and password, or make sure your passwords match."
            println("Registration had an error")
    }
    if error != "" {
        displayAlert("Error in Registration", error: error)
    } else {

    //Sign Up User
    var user = PFUser()

    //Resize Profile Picture
    let size = CGSizeApplyAffineTransform(profileImage.size, CGAffineTransformMakeScale(0.5, 0.5))
    let hasAlpha = true
    let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
    UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
    profileImage.drawInRect(CGRect(origin: CGPointZero, size: size))
    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //User Information
    user.password = userPasswordTwo.text
    user.email = userEmailAddress.text
    user.username = userEmailAddress.text
        if isThereImage == false {
            displayAlert("Please upload a picture for your profile.", error: error)
        }else if isThereImage == true {
            var imageData = UIImagePNGRepresentation(scaledImage)
            var imageFile = PFFile(name: userEmailAddress.text + ".png", data:imageData)
            user.setObject(imageFile, forKey: "userProfileImage")
        }
    user.setObject("", forKey: "firstName")
    user.setObject("", forKey: "lastName")
    user.setObject("", forKey: "userLocation")

    //Insert Activity Indicator here
    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()
    //-------------------------------

    user.signUpInBackgroundWithBlock {
        (succeeded: Bool!, signupError: NSError!) -> Void in
            //Stop activity indicator whether there is an error or not
            self.activityIndicator.stopAnimating()
            UIApplication.sharedApplication().endIgnoringInteractionEvents()
            if signupError == nil {
            // Hooray! Let them use the app now.
            println("Registration Completed")
            } else {
                //Keep this here!
                if let errorString = signupError.userInfo?["error"] as? NSString{
                    error = errorString
                } else {
                    error = "Please try again later."
                }
            self.displayAlert("Could not Sign Up", error: error)
            println(signupError)
            }
        }
    }
    //Print Confirmation to Cortana
}

//---------------------------------------

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    passwordConfirmationMatch.hidden = true
    //UITextField Delegate
    self.userEmailAddress.delegate = self
    self.userPasswordOne.delegate = self
    self.userPasswordTwo.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//Password Matching Function
func passwordCheck() {
    if userPasswordTwo.text == userPasswordOne.text {
        passwordConfirmationMatch.hidden = false
        confirmedPassword = true
        println("Password match")
    } else {
        passwordConfirmationMatch.hidden = true
        confirmedPassword = false
        println("Passwords don't match")
    }
}

//Handle Keyboard

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
    passwordCheck()
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {
    userEmailAddress.resignFirstResponder()
    userPasswordOne.resignFirstResponder()
    userPasswordTwo.resignFirstResponder()
    passwordCheck()
    return true
}
}
4

1 回答 1

2

您收到的错误表明当您的代码尝试访问它时,您的一个已声明为可选的变量为 nil。

您是否从错误中获得更多信息?例如变量的名称?如果没有,请使用一些断点来查找罪魁祸首,并确保在使用它的时候它不为零。

于 2015-02-09T13:16:52.770 回答