Swift shows Expected declaration error while using firebase [duplicate] - swift

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 ?? "")
})
}

Related

Does not add a user to Firebase

I am trying to add users to my Firebase cloud
I connected my project to the console.firebase
While I fill in the email and password it is not adding to my firebase.
I have the following code:
#IBAction func registerButton(_ sender: Any) {
signUp()
}
this is a button for register
and this is the func signup:
func signUp (){
let name = nameValue.text
let password = passwordValue.text
let email = emailValue.text
if (!password!.isEmpty && !email!.isEmpty) {
Auth.auth().createUser(withEmail: email ?? "", password: password ?? "") { (result, error) in
if error == nil {
if let result = result {
}
}
}
}
else {
showAlert()
}
}
Can anybody help to figure out this problem?
here is the solution to my problem:
if (!name!.isEmpty && !password!.isEmpty && !email!.isEmpty) {
Auth.auth().createUser(withEmail: email ?? "", password: password ?? "") { (authResult, error) in
if let e = error {
print(e.localizedDescription)
} else {
// self.performSegue(withIdentifier: "main", sender: self)
}
}
}

Check Firebase error and if textFields are empty before creating user

I´m trying to check for signup errors and if textFields is empty. This is kind of working, but it allows the user to register the user if the nameTextFieldand the addressTextFieldis empty. The alert poops up correctly though.
#IBAction func registerButton(_ sender: UIButton) {
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { user, error in
if error != nil {
if let errCode = AuthErrorCode(rawValue: error!._code) {
switch errCode {
case .invalidEmail:
self.errorMsg(title: "Error", message: "E-mail address format wrong")
case .emailAlreadyInUse:
self.errorMsg(title: "Error", message: "E-mail is already in use")
case .weakPassword:
self.errorMsg(title: "Error", message: "Weak password. Need at least 6 characters")
default:
print("Create User Error: \(error!)")
}
}
return
} else {
//Display errormsg for missing entry
if (self.nameTextField.text?.isEmpty)! {
self.missingText(title: "Ooops", message: "Please enter your name")
if (self.addressTextField.text?.isEmpty)! {
self.missingText(title: "Ooops", message: "Please enter your address")
}
} else {
//Register userinfo in Firebase
let ref = Database.database().reference()
let usersRefrence = ref.child("users")
let uid = user?.user.uid
let newUserRefrence = usersRefrence.child(uid!)
newUserRefrence.setValue(["Name": self.nameTextField.text!, "Address": self.addressTextField.text!])
}
self.registrationConfirmation(title: "Great", message: "Please sign in with the registered user")
}
})
}
validate textfield before going to auth.
guard let email = emailTextField.text, email.isValidEmail(), let password = passwordTextField.text, password != "" else {
// show error for nil values
return
}
// go with Autth
Auth.auth().createUser(withEmail: email, password: password, completion
make an extension for validating email
extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}

Swift Firebase Facebook Login - Gets Name, but email returns nil

Recently my facebook login hasn't been working. It doesn't save into my database but in Firebase authentication it shows someone signed in with facebook but the email is blank. It doesn't save any data to my database which it should. The email is returning nil. My google sign in works. I've checked all the connections and they all seem to be fine. (I could have missed something) anyone have any suggestions on what connections I should check? Not sure what to do...
More Info
I printed my graph request... not sure if this helps to debug
let loginManager: FBSDKLoginManager = FBSDKLoginManager()
loginManager.logIn(withReadPermissions: self.facebookPermissions, from: self, handler: { (result, error) in
if error != nil {
loginManager.logOut()
let message: String = "An error has occured. \(String(describing: error))"
let alertView = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "Ok ", style: UIAlertActionStyle.default, handler: nil))
self.present(alertView, animated: true, completion: nil)
} else if (result?.isCancelled)! {
// user cancelled login
loginManager.logOut()
} else {
let accessToken = FBSDKAccessToken.current()
guard let accessTokenString = accessToken?.tokenString else { return }
let credential = FacebookAuthProvider.credential(withAccessToken: accessTokenString)
Auth.auth().signIn(with: credential) { (user, error) in
if (error != nil) {
// handle error
print(error ?? "Error")
} else {
let ref = Database.database().reference()
// guard for user id
guard let uid = user?.uid else {
return
}
let usersReference = ref.child("user_profiles").child(uid)
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if error != nil {
// Process error
print("Error: \(String(describing: error))")
} else {
guard let data: [String:AnyObject] = result as? [String:AnyObject] else {
print("Can't pull data from JSON")
return
}
guard let userName: String = data["name"] as? String else {
print("Can't pull username from JSON")
return
}
guard let userID: String = data["id"] as? String else {
print("Can't pull ID from JSON")
return
}
let imgURLString = "http://graph.facebook.com/\(userID)/picture?type=large" as String
guard let userEmail: String = data["email"] as? String else {
print("Can't pull email from JSON")
print("Error: \(String(describing: error))")
return
}
// initial # posts = 0
let values = ["name": userName, "email": userEmail, "facebookID": userID, "profPicString": imgURLString] as [String : Any]
// update database with new user
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
// error in database save
if err != nil {
print(err ?? "Error saving user to database")
return
}
})
}
})
self.dismiss(animated: false, completion: nil)
// Present the main view
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Customer Profile") {
UIApplication.shared.keyWindow?.rootViewController = viewController
self.dismiss(animated: true, completion: nil)
}
}
}
}
})
Using Swift 5 I found the email inside providerData which is an array of FIRUserInfo:
if AccessToken.current != nil {
let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
Auth.auth().signIn(with: credential) { (res, err) in
if err != nil || res == nil {
//...
return
}
guard let providerData = res?.user.providerData else {
//...
return
}
for firUserInfo in providerData {
print(firUserInfo.providerID)
print(firUserInfo.email ?? "Email not found")
}
}
}

Function will not call Swift 3

#IBAction func signup(_ sender: Any) {
print("began signup process")
guard let fullname = fullnameField.text, fullname != "" else {
print("FULLNAME field is empty")
return
}
guard let username = usernameField.text, username != "" else {
print("USERNAME field is empty")
return
}
guard let email = emailField.text, email != "" else {
print("EMAIL field is empty")
return
}
guard let password = passwordField.text, password != "" else {
print("PASSWORD field is empty")
return
}
print("all fields good")
mainActivityIndicator.startAnimating()
self.checkUsernameAvailability(username: username, completion: {
result in
print("starting check")
...
})
print("finished the function")
}
The issue is basically that nothing inside of the checkUsernameAvailability function will call.
The console looks like this:
began signup process
all fields good
finished the function
it does not print 'starting check' or run any code at all inside of the function.
This is probably a rookie error and I am sorry if it is a stupid question.
Future thanks.
P.S I checked the entire console and there is no error relating to this.
EDIT: Here is the code inside the function
func checkUsernameAvailability(username: String, completion: #escaping (Bool) -> Void) {
_ = Database.database().reference().child("usernames").observe(.childAdded, with: {
snapshot in
print("checking username availability")
print(snapshot)
completion(true)
let dict = snapshot.value as? [String: AnyObject]
for handled in (dict?.values)! {
print("stumbled")
print(handled)
if username.lowercased() == handled.lowercased {
completion(false)
}
}
})
}
And...
self.checkUsernameAvailability(username: username, completion: {
result in
print("starting check")
if result == false {
print("username is taken")
self.mainActivityIndicator.stopAnimating()
return
} else {
Auth.auth().createUser(withEmail: email, password: password, completion: {
(user, error) in
if error != nil {
print(error ?? "ERROR OCCURED")
self.mainActivityIndicator.stopAnimating()
return
}
let ref = Database.database().reference()
ref.child("~/users/\(user?.uid ?? "0")/username").setValue(username.lowercased())
ref.child("~/users/\(user?.uid ?? "0")/fullname").setValue(fullname)
ref.child("usernames/\(user?.uid ?? "0")").setValue(username.lowercased())
self.mainActivityIndicator.stopAnimating()
})
}
})
The Database.database().reference().child("usernames").observe call simply never calls the with block. I would assume that block is called when the event .childAdded is observed, but I see no code that would add a child. To me this looks like you are setting up an asynchronous observer, so this code will not run when you make the call, it will run when the monitored event takes place.

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