[英]Read response from Facebook Graph Request in Swift 4
我正在嘗試使用Graph API將Facebook朋友列表添加到我的Swift iOS應用中。
我正在努力研究如何實際訪問從Facebook發送回的數據。
我得到的響應如下所示:
success(FacebookCore.GraphResponse(rawResponse: Optional({
"first_name" = Jamie;
id = 1626917907360895;
"last_name" = McAllister;
name = "Jamie McAllister";
picture = {
data = {
height = 50;
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/12994335_1101318013254223_4481895970110564364_n.jpg?oh=d10209f113213981e4417e7f6f3f82d8&oe=5A91F135";
width = 50;
};
};
})))
由於我是唯一的注冊用戶,因此我的圖表Request暫時是/me
。 但是響應中的所有字段都是我要從朋友列表中請求的
圖形請求如下所示:
var graph = GraphRequest.init(graphPath: "me")
graph.parameters = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
graph.start({ (response, data) in
print("======GRAPH=====")
print(data)
})
因此,我希望能夠采用GraphResponse
,使其成為數組並將其分配給變量。 我完全被這個困擾。
希望這對Swift 4.2有幫助
func getFbId(){
if(AccessToken.current != nil){
let req = GraphRequest(graphPath: "me", parameters: ["fields": "email,first_name,last_name,gender,picture"], accessToken: AccessToken.current, httpMethod: GraphRequestHTTPMethod(rawValue: "GET")!)
req.start({ (connection, result) in
switch result {
case .failed(let error):
print(error)
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print(responseDictionary)
let firstNameFB = responseDictionary["first_name"] as? String
let lastNameFB = responseDictionary["last_name"] as? String
let socialIdFB = responseDictionary["id"] as? String
let genderFB = responseDictionary["gender"] as? String
let pictureUrlFB = responseDictionary["picture"] as? [String:Any]
let photoData = pictureUrlFB!["data"] as? [String:Any]
let photoUrl = photoData!["url"] as? String
print(firstNameFB, lastNameFB, socialIdFB, genderFB, photoUrl)
}
}
})
}
}
要讀取來自Facebook Graph Request的響應,請使用以下代碼行
let info = data as! [String : AnyObject]
if info["name"] as? String != nil {
self.usernameLbl.text = info["name"] as! String
}
希望這個能對您有所幫助
Graph請求開始完成塊已更改為需要3個參數,而不是2個。
因此,您將得到以下內容(請注意,開始塊中已通過了3個項目 [連接,結果和錯誤]):
let params = ["fields" : "email, first_name, id, picture"]
let graphRequest = GraphRequest(graphPath: "me", parameters: params)
graphRequest.start{
(connection, result, error in
if error == nil {
if let responseDictionary = result as? NSDictionary {
UserProfile.userName = responseDictionary["first_name"] as? String ?? "User"
UserProfile.userID = responseDictionary["id"] as! String
var pictureUrl = ""
if let picture = responseDictionary["picture"] as? NSDictionary, let data = picture["data"] as? NSDictionary, let url = data["url"] as? String {
pictureUrl = url
}
}
}else{
print("error in graph request:", error)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.