I am currently using the Facebook iOS SDK to capture email, first, and last name successfully in my app. However, for some reason, I am having difficulty capturing the location information such as city, and country for the user.
Here is my relevant code:
override func viewDidLoad() {
super.viewDidLoad()
fbLoginButton.delegate = self
fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]
}
extension RegisterViewController: FBSDKLoginButtonDelegate {
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Did log out of facebook")
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
print("Successfully logged in with facebook...")
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, first_name, last_name, email, location{location}"]).start { (connection, result, err) in
if err != nil {
print("Failed to start graph request:", err)
return
}
print(result)
let fbDetails = result as! NSDictionary
let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary //code crashes here
let locationContents : NSDictionary! = location.value(forKey: "location") as! NSDictionary
let city: String! = locationContents.value(forKey: "city") as? String
let state: String! = locationContents.value(forKey: "state") as? String
let country: String! = locationContents.value(forKey: "country") as? String
print(fbDetails)
print("city:", city)
print("state:", state)
print("country:", country)
}
}
}
When I run the code, in my console, I see the output for email, first_name, last_name, id, name, but nothing for location, and my app crashes with:
fatal error: unexpectedly found nil while unwrapping an Optional value
when it reaches the line:
let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary
What am I doing wrong?
You need to add 'user_location' to your read_permission.
fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]
Remember to verify this permission in your fb application.(user_location is not default allowed permissions)