-1

When I hit my sign up button without uploading an image I get a crash. If I upload a photo without filling out the rest of the textFields I get a pop up alert. How can I get the same alert when there is no photo being uploaded? The error I get is

fatal error: unexpectedly found nil while unwrapping an Optional value

@IBAction func signUpAction(_ sender: Any) {
    let email = emailTextField.text!.lowercased()
    let finalEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
    let location = locationTextField.text!
    let biography = biographyTextField.text!
    let username = usernameTextField.text!
    let password = passwordTextField.text!
    let firstLastName = firstLastNameTextField.text!
    let pictureData = UIImageJPEGRepresentation(self.userImageView.image!, 0.70)

    if  finalEmail.isEmpty || location.isEmpty || biography.isEmpty || username.isEmpty || password.isEmpty {
        self.view.endEditing(true)
        let alertController = UIAlertController(title: "OOPS", message: " You must fill all the fields", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alertController, animated: true, completion: nil)

    }else {
        self.view.endEditing(true)
        authService.signUP(username: username, email: finalEmail, location: location, biography: biography, password: password, pictureData: pictureData as NSData!)

    }


}

  var authService = AuthService()



struct AuthService{

var dataBaseRef: DatabaseReference!{
    return Database.database().reference()
}
var storageRef: StorageReference!{
    return Storage.storage().reference()
}

func signUP(username: String, email: String, location: String, biography: String, password: String, pictureData: NSData!) {

    Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
        if error == nil{

            self.setUserInfo(user: user, username: username, location: location, biography: biography, password: password, pictureData: pictureData)

        }else{
            print(error?.localizedDescription)
        }
    }


}

private func setUserInfo(user: User!, username: String, location: String, biography: String, password: String, pictureData: NSData!){

    let imagePath = "profileImage\(user.uid)/userPic.jpg"
    let imageRef = storageRef.child(imagePath)

let metaData = StorageMetadata()
    metaData.contentType = "image/jpeg"
    imageRef.putData(pictureData as Data, metadata: metaData){(newMetaData, error)
        in
        if error == nil{
            let changeRequest = user.createProfileChangeRequest()
            changeRequest.displayName = username
            if let photoURL = newMetaData!.downloadURL(){
                changeRequest.photoURL = photoURL

            }
            changeRequest.commitChanges(completion: { (error) in
                if error == nil{

                    self.saveUserInfo(user: user, username: username, location: location, biography: biography, password: password)

                    print("user info set")

                }else{
                    print(error?.localizedDescription)
                }
            })

        }else{
            print(error?.localizedDescription)
        }

    }

}

private func saveUserInfo(user: User!, username: String, location: String, biography: String, password: String){

    let userInfo = ["email": user.email!, "username": username, "location": location, "biography": biography, "uid": user.uid, "photoURL": String(describing: user.photoURL!)]

    let userRef = dataBaseRef.child("users").child(user.uid)
    userRef.setValue(userInfo) { (error, ref) in
        if error == nil{
            print("USER SAVED")
            self.logIn(email: user.email!, password: password)
        }else{
            print(error?.localizedDescription)

        }
    }

}

func logIn(email: String, password: String){

    Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
        if error == nil {
            if let user = user {
                print("\(user.displayName!) has been signed in")

                let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
                appDel.logUser()

            }else{
                print(error?.localizedDescription)

            }

        }
    }
}

}

user8000557
  • 137
  • 8
  • Try adding this condition `|| pictureData == nil` after `|| password.isEmpty` in `if` statement.Also I would suggest you make changes in your code and try removing `!` from your code and use `if let` or `guard` statements in your code to safely unwrap your optionals – 3stud1ant3 Oct 18 '17 at 02:29
  • still getting the same error after adding || pictureData == nil to my if statement – user8000557 Oct 18 '17 at 02:33

1 Answers1

0

I think you need to add this:

var pictureData: NSData?   //Try using Data in your code in swift

if let imageView = self.userImageView.image {
     pictureData = UIImageJPEGRepresentation(imageView, 0.70)
}

then add this statement || pictureData == nil after || password.isEmpty in if statement

3stud1ant3
  • 3,586
  • 2
  • 12
  • 15
  • Please don't answer duplicate questions. Instead, vote to close them. – JAL Oct 18 '17 at 03:04
  • Also, this is a bad answer. Why would you force unwrap `self.userImageView.image` after assigning `imageView` with an `if let`? – JAL Oct 18 '17 at 03:05
  • Sorry my bad, I cant delete my answer, so I updated it and corrected the mistake that I made , thanks for you input – 3stud1ant3 Oct 18 '17 at 03:17