针对Swift 5
首先添加所需的字段。
let params = ["fields": "first_name, last_name, email, picture"]
创建图形请求
let graphRequest = GraphRequest(graphPath: "me", parameters: params, tokenString: token.tokenString, version: nil, httpMethod: .get)
graphRequest.start { (connection, result, error) in }
您将会得到JSON格式的结果。
{
"first_name": "",
"last_name": "",
"picture": {
"data": {
"height": 50,
"is_silhouette": false,
"url": "",
"width": 50
}
},
"id": ""
}
根据JSON响应,捕获结果。
if let error = error {
print("Facebook graph request error: \(error)")
} else {
print("Facebook graph request successful!")
guard let json = result as? NSDictionary else { return }
if let id = json["id"] as? String {
print("\(id)")
}
if let email = json["email"] as? String {
print("\(email)")
}
if let firstName = json["first_name"] as? String {
print("\(firstName)")
}
if let lastName = json["last_name"] as? String {
print("\(lastName)")
}
if let profilePicObj = json["picture"] as? [String:Any] {
if let profilePicData = profilePicObj["data"] as? [String:Any] {
print("\(profilePicData)")
if let profilePic = profilePicData["url"] as? String {
print("\(profilePic)")
}
}
}
}
}
您可以通过在参数中发送所需的宽度来获取定制宽度的个人资料图片。
let params = ["fields": "first_name, last_name, email, picture.width(480)"]
这是整个代码的样子。
if let token = AccessToken.current {
let params = ["fields": "first_name, last_name, email, picture.width(480)"]
let graphRequest = GraphRequest(graphPath: "me", parameters: params,
tokenString: token.tokenString, version: nil, httpMethod: .get)
graphRequest.start { (connection, result, error) in
if let error = error {
print("Facebook graph request error: \(error)")
} else {
print("Facebook graph request successful!")
guard let json = result as? NSDictionary else { return }
if let id = json["id"] as? String {
print("\(id)")
}
if let email = json["email"] as? String {
print("\(email)")
}
if let firstName = json["first_name"] as? String {
print("\(firstName)")
}
if let lastName = json["last_name"] as? String {
print("\(lastName)")
}
if let profilePicObj = json["picture"] as? [String:Any] {
if let profilePicData = profilePicObj["data"] as? [String:Any] {
print("\(profilePicData)")
if let profilePic = profilePicData["url"] as? String {
print("\(profilePic)")
}
}
}
}
}
}
请查看图形API Explorer以获取更多字段。