Hello i am trying to retrieve my email from facebook as i am playing the facebook ios sdk using swift. IOS platform is 10, swift 3 and Xcode 8. I followed tutorials online but having trouble retrieving email.
below is my code:
if FBSDKAccessToken.current() == nil {
print("I got token")
let fbButton = FBSDKLoginButton()
fbButton.readPermissions = ["public_profile", "email", "user_friends"]
view.addSubview(fbButton)
fbButton.center = view.center
fbButton.delegate = self
self.fetchprofile()
}
else {
print("Dont have token")
let loginView : FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error.localizedDescription)
return
}
print("I'm in")
fetchprofile()
}
func fetchprofile() {
print("Getting profile")
let parameters = ["fields": "email"]
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: parameters, httpMethod: "GET")
graphRequest.start(completionHandler: {(connection, result, error) -> Void in
if error != nil {
print("Error retrieving details: \(error?.localizedDescription)")
return
}
guard let result = result as? [String:[AnyObject]], let email = result["email"] else {
return
}
print("Email: \(email)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
self.view.backgroundColor = UIColor.red
})
}
and in my appdelegate.swift file :
//have both google and facebook signin. Google works but facebook doesn't
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String,
annotation: options[UIApplicationOpenURLOptionsKey.annotation]) ||
FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
I am able to log in and log out but not able to retrieve email.
UPDATE Actually when i actually pass print(email) i can see it on the console as an optional statement. I'm having trouble displaying it without optional statment
I have solved the problem in this way:
func fetchProfile(){
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields" : "email, name, id, gender"])
.start(completionHandler: { (connection, result, error) in
guard let result = result as? NSDictionary, let email = result["email"] as? String,
let user_name = result["name"] as? String,
let user_gender = result["gender"] as? String,
let user_id_fb = result["id"] as? String else {
return
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With