Thread 1 Fatal Error Optional Value Swift [duplicate] - swift

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 4 years ago.
#IBAction func login(_ sender: Any) {
guard emailField.text != "", passField.text != "" else {return}
Auth.auth().signIn(withEmail:emailField.text!,password:passField.text!, completion: { (user, error) in
if let error = error {
print(error.localizedDescription)
I get this error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

Try:
guard let email = self.emailField.text, let password = self.passField.text else { return }
if email != "" && pass != "" {
Auth.auth().signIn(withEmail: email, password: password) { (user, err) in
if err != nil { print(err.localizedDescription); return }
// do something
}
}

Related

How to handle Firebase Auth Errors? / Swift / Firebase

Hey guys can someone tell me how to handle this? I tried a lot but if I correct the one error another one is appearing...
Thanks in advance
Auth.auth().createUser(withEmail: eMailTextField.text!, password: passwordTextField.text!) { (data, error) in
if error != nil {
if let errCode = error as NSError? {
guard let errorCode = AuthErrorCode(rawValue: error) else {
print("there was an error logging in but it could not be matched with a firebase code")
return
}
switch errorCode {
case .FIRAuthErrorCodeNetworkError:
print("No Internet Connection")
case .ErrorCodeEmailAlreadyInUse:
print("in use")
default:
print("Create User Error: \(error!)")
}
}
} else {
print("all good... continue")
}
You can bridge to NSError and then create the AuthErrorCode based on error.code:
Auth.auth().createUser(withEmail: "MyEmail", password: "MyPassword") { authResult, error in
if error != nil, let error = error as NSError? {
if let errorCode = AuthErrorCode(rawValue: error.code) {
switch errorCode {
case .invalidEmail:
break
case .emailAlreadyInUse:
break
default:
break
}
}
} else {
//no error
}
}
Note that I only listed a couple of the errorCode possibilities - there's quite an extensive list of them.

How to have code inside of a guard else statement in swift?

I have the following code:
#IBAction func loginTapped(_ sender: Any) {
let error = validateFieldsSignIn()
if error != nil {
showErrorSignIn(error!)
} else {
guard let emailsignin = emailSignIn?.text!.trimmingCharacters(in: .whitespacesAndNewlines),
let passwordsignin = passwordSignIn?.text!.trimmingCharacters(in: .whitespacesAndNewlines) else {
return showErrorSignIn("Fill in all fields")
}
Auth.auth().signIn(withEmail: emailsignin, password: passwordsignin) { (user, error) in
if error != nil {
print("There was an error")
self.errorLabel3.text = "Invalid username or password"
self.errorLabel3.alpha = 1
} else {
self.transitionToHome()
}
}
}
}
Although unless the fields aren't filled in the else statement gets triggered and the error label says fill in all fields, essential the code that is getting triggered is this:
else {
return showErrorSignIn("Fill in all fields")
}
I tried putting the Auth.auth().signIn() inside the else block although I got the following error:
Variable declared in 'guard' condition is not usable in its body
How do I fix this error message?

Swift shows Expected declaration error while using firebase [duplicate]

This question already has answers here:
swift compiler shows Expected declaration error? [duplicate]
(3 answers)
Closed 4 years ago.
I'm new in Swift and I'm making a pretty simple login page using Firebase. I have this code:
guard fullNameTextField.text != "", emailTextField.text != "", passwordTextField.text != "", confirmPasswordTextField.text != ""
else {
return
}
}
if passwordTextField.text == confirmPasswordTextField.text {
//MARK: Firebase autenthication
FIRAuth.auth()?.createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion:{
(user,error)in
if let error = error {
print(error.localizedDescription)
}
and the Xcode says that there is Expected a declaration error. I would be thankful if anyone could help me with this because I think I have tried everything.
I think you need to update to latest version
Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
// ...
guard let user = authResult?.user else { return }
}
Have a look here Docs
You should avoid force unwrapping. Your code should look like this:
guard let name = fullNameTextField.text, name.count > 0 else { return }
guard let email = emailTextField.text, email.count > 0 else { return }
guard let password = passwordTextField.text, password.count > 0 else { return }
guard let confirmPassword = confirmPasswordTextField.text, confirmPassword.count > 0 else { return }
if password == confirmPassword {
Auth.auth().createUser(withEmail: email, password: password, completion: { (result, error) in
if let error = error {
print("Failed to create new user", error)
return
}
print("Successfully created user:", result?.user.uid ?? "")
})
}

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

I am new in Swift. My question is I am not sure how to unwrapping the optional value. When I print the object.objectForKey("profile_picture"), I can see Optional(<PFFile: 0x7fb3fd8344d0>).
let userQuery = PFUser.query()
//first_name is unique in Parse. So, I expect there is only 1 object I can find.
userQuery?.whereKey("first_name", equalTo: currentUser)
userQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
}
for object in objects! {
if object.objectForKey("profile_picture") != nil {
print(object.objectForKey("profile_picture"))
self.userProfilePicture.image = UIImage(data: object.objectForKey("profile_pricture")! as! NSData)
}
}
})
You'd use if let to perform "optional binding", only performing the block if the result in question is not nil (and binding the variable profilePicture to the unwrapped value in the process).
It would be something like:
userQuery?.findObjectsInBackgroundWithBlock { objects, error in
guard error == nil && objects != nil else {
print(error)
return
}
for object in objects! {
if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
print(profilePicture)
do {
let data = try profilePicture.getData()
self.userProfilePicture.image = UIImage(data: data)
} catch let imageDataError {
print(imageDataError)
}
}
}
}
Or, if you want to get data asynchronously, perhaps:
userQuery?.findObjectsInBackgroundWithBlock { objects, error in
guard error == nil && objects != nil else {
print(error)
return
}
for object in objects! {
if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
profilePicture.getDataInBackgroundWithBlock { data, error in
guard data != nil && error == nil else {
print(error)
return
}
self.userProfilePicture.image = UIImage(data: data!)
}
}
}
}
It would be something along those lines, using if let to unwrap that optional. And you then have to get the NSData associated with that the PFFile object (from the getData method or getDataInBackgroundWithBlock, presumably).
See Optional Binding discussion in The Swift Programming Language.

Swift 2.0 Parse Login

So I've been attempting to update my code to Swift 2.0 syntax, but I can't seem to get my Parse login to work. I looked over the documentation changes and added the result block for my login, but I'm getting the error "'(, ) throws -> Void' is not convertible to 'PFUserResultBlock?'"
Here is the line of code:
PFUser.logInWithUsernameInBackground(usernameTextField.text!, password: passwordTextField.text!, block: { (user,error) -> Void in
if user != nil {
This Code might solve your problem.
PFUser.logInWithUsername(inBackground: emailTextField.text!, password: passwordTextField.text!, block: { (user, error) in
self.activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil {
var displayErrorMessage = "Please try again later"
let error = error as NSError?
if let errorMessage = error?.userInfo["error"] as? String {
displayErrorMessage = errorMessage
}
self.createAlert(title: "Login Error", message: displayErrorMessage)
} else {
print("logged inn")
self.performSegue(withIdentifier: "showUserTable", sender: self)
}
})
Try this version
PFUser.logInWithUsernameInBackground(usernameTextField.text!, password: passwordTextField.text!) { (user:PFUser?, error:NSError?) -> Void in
if user != nil {
print("Login Successful")
} else {
print("Login Failed")
}
}