xcode 如何在 Swift 3 中处理 FBSDKGraphRequest 的响应数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39384238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:12:47  来源:igfitidea点击:

How to process the response data of FBSDKGraphRequest in Swift 3

swiftxcodefacebook-graph-apiswift3

提问by KD.

I have integrated the FB latest SDK(non-swift) and log in is working fine. All I need to know how do I parse the Graph response data since its not a valid JSON

我已经集成了 FB 最新的 SDK(非 swift)并且登录工作正常。我只需要知道如何解析 Graph 响应数据,因为它不是有效的 JSON

Working code:

工作代码:

     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)

        }
    })
}

With output:

有输出:

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

So what format should I convert the above data to get values like URL or first_name etc?

那么我应该将上述数据转换为什么格式来获取 URL 或 first_name 等值?

Also I tried converting to NSDictionaryand got error:

我也尝试转换为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)
                }

            }
        })
    }

回答by Bista

You can simply do it as follows:

您可以简单地执行以下操作:

let data:[String:AnyObject] = result as! [String : AnyObject]
print(data["first_name"]!)

Swift 3:

斯威夫特 3:

Safe unwrapping & Anyinstead of AnyObject

安全解包 &Any而不是AnyObject

if let data = result as? [String:Any] {

}

回答by rptwsthi

Swift 5Code for question and issue and solution:

问题和问题以及解决方案的Swift 5代码:

Implementation:

执行:

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

Output:

输出:

rDic =  {
    email = "[email protected]";
    "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.: Thanks to KD and Bista their question and answer helped me figure this.

PS:感谢 KD 和 Bista,他们的问答帮助我解决了这个问题。