我已经集成了FB最新的SDK(非swift),登录工作正常。我需要知道如何解析Graph响应数据,因为它不是有效的JSON
工作代码:
func configureFacebook()
{
login.readPermissions = ["public_profile", "email", "user_friends"];
login.delegate = self
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("Login buttoon clicked")
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print(result)
}
})
}
输出:
Login button clicked
Optional({
"first_name" = KD;
id = 10154CXXX;
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/XXXn.jpg?oh=a75a5c1b868fa63XXX146A";
};
};
})
那么我应该将上述数据转换为什么格式来获取URL或first_name等值。
此外,我绑定转换为NSDictionary并收到错误:
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("Login buttoon clicked")
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil)
{
print("Error: \(error)")
}
else
{
do {
let fbResult = try JSONSerialization.jsonObject(with: result as! Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(fbResult.value(forKey: "name"))
} catch {
print(error)
}
}
})
}
答案 0 :(得分:20)
您可以按照以下方式执行此操作:
let data:[String:AnyObject] = result as! [String : AnyObject]
print(data["first_name"]!)
斯威夫特3:
安全展开& Any
代替AnyObject
if let data = result as? [String:Any] {
}
答案 1 :(得分:1)
Swift 5 用于问题,解决方案的代码:
实现:
let graphRequest:GraphRequest = GraphRequest(graphPath: "me", parameters: ["fields":"first_name,email,picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil) {
print("Error: \(String(describing: error))")
}
else {
guard let rDic = result as? NSDictionary else {
SVProgressHUD.showError(withStatus: "facebook Did not allowed loading email, please set that while updating profile.")
return
}
print("rDic = ", rDic)
}
})
输出:
rDic = {
email = "you@know.it";
"first_name" = Mr. Me;
id = #################;
picture = {
data = {
height = 32;
"is_silhouette" = 0;
url = "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=################&height=200&width=200&ext=################&hash=################";
width = 32;
};
};
}
P.S .:感谢KD和Bista,他们的问题和答案帮助我弄清了这一点。