如何从Facebook Graph API的GraphResponseProtocol访问数据

时间:2018-07-24 14:01:34

标签: ios swift facebook facebook-graph-api

我在Swift上还很新,现在正在使用Facebook graph api。我无法访问来自图形请求的数据。

struct MyProfileRequest: GraphRequestProtocol {
    struct Response: GraphResponseProtocol {

        init(rawResponse: Any?) {

            // Decode JSON from rawResponse into other properties here.
            let json = JSON(rawResponse!)
            let userDef : [String : String] = [
                "username" : json["name"].stringValue,
                "lastname" : json["last_name"].stringValue, 
                "shortname" : json["short_name"].stringValue, 
                "name_format" : json["name_format"].stringValue
            ]
        }
    }

    var graphPath = "/me"
    var parameters: [String : Any]? = [ "fields": "id, name, last_name, name_format, short_name"]
    var accessToken = AccessToken.current
    var httpMethod: GraphRequestHTTPMethod = .GET
    var apiVersion: GraphAPIVersion = .defaultVersion
}

我需要访问该块之外的“ userDef”字典。

1 个答案:

答案 0 :(得分:2)

很简单,只需检查此示例代码

struct MyProfileRequest: GraphRequestProtocol {
    struct Response: GraphResponseProtocol {
        var name:String?
        var email:String?
        var id:String?
        init(rawResponse: Any?) {
            print(rawResponse)
            // Decode JSON from rawResponse into other properties here.
            if let response = rawResponse as? [String:Any] {
                name = (response["name"] as? String) ?? ""
                email = (response["email"] as? String) ?? ""
                id = (response["id"] as? String) ?? ""
            }
        }
    }

    var graphPath = "/me"
    var parameters: [String : Any]? = ["fields": "id, name,email"]
    var accessToken = AccessToken.current
    var httpMethod: GraphRequestHTTPMethod = .GET
    var apiVersion: GraphAPIVersion = .defaultVersion


}

如何访问nameemailid

    MyProfileRequest().start {[unowned self]  (req, result) in
        switch result {
        case .success(let values): // Here is your values

            print("Custom Graph Request Succeeded: \(values)")
            print(values.name)

        case .failed(let error):
            print("Custom Graph Request Failed: \(error)")
        }
    }