我目前正在使用 Facebook iOS SDK 在我的应用程序中成功捕获电子邮件、名字和姓氏。但是,由于某种原因,我很难为用户捕获位置信息,例如城市和国家/地区。
这是我的相关代码:
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)
}
}
}
当我运行代码时,在我的控制台中,我看到了电子邮件、名字、姓氏、ID、姓名的输出,但没有任何位置信息,我的应用程序崩溃了:
fatal error: unexpectedly found nil while unwrapping an Optional value
当它到达线时:
let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary
谁能看到我做错了什么?
您需要将“user_location”添加到您的 read_permission 中。
fbLoginButton.readPermissions = ["email", "public_profile", "user_location"]
记得在你的 fb 应用中验证这个权限。(user_location 不是默认允许的权限)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句