【问题标题】:How to access data from Facebook Graph API's GraphResponseProtocol如何从 Facebook Graph API GraphResponse 协议访问数据
【发布时间】:2019-01-01 04:39:45
【问题描述】:

我是 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”字典。

【问题讨论】:

    标签: ios swift facebook facebook-graph-api


    【解决方案1】:

    这很简单,看看这个示例代码就行了

    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)")
            }
        }
    

    【讨论】:

    • 首先,感谢您的快速回答,但我收到“'loginVC' 类型的值没有成员'showAlert'”错误
    • @TolgaKarameşe 抱歉忘记删除,现在检查
    • 非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多