swift - 找不到 fatal error : unexpectedly found nil while unwrapping an Optional value

标签 swift fatal-error null optional-values

<分区>

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

fatal error: unexpectedly found nil while unwrapping an Optional value.

谁能帮我找出这个错误?

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
}
}

最佳答案

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

您是否从错误中获得了更多信息?比如变量名?如果不是,请使用一些断点来找到罪魁祸首,并确保在使用它的时候它不是 nil。

关于swift - 找不到 fatal error : unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410631/

相关文章:

php - 第 463 行的 fatal error : Call to a member function getModelInstance() on a non-object in/Applications/XAMPP/xamppfiles/htdocs/magento/app/Mage. php

c# - 在 foreach 循环中检查 null

xcode - Swift:如何将 UIImageView 的缩放区域显示到另一个 UIImageView 中

java - Android mupdf java.lang.UnsatisfiedLinkError : dlopen failed: cannot locate symbol "atof"

ios - YY/MM dateString 到日期组件

php - 在不在 ReflectionFunction->invoke() 的对象上下文中时使用 $this

c# - 什么是NullReferenceException,如何解决?

sql - 如何在SQL oracle的Select语句中声明空列

swift - 如何在 ARKit 3.0 中启用 `Depth of Field` 选项?

ios - 如何在GMSMapView中获取动画折线路线,使其在 map 移动时随 map 一起移动?