首页 > 解决方案 > 如何从 FBSDKGraphRequest 结果将用户名设置为 UITextField

问题描述

我正在使用 Xcode 10、Swift 5,并且试图将 UITextField 设置为我从 Facebook 检索到的用户名。我已成功检索到结果中的 ID、电子邮件和名称,但是当我将结果发送到文本字段时,包含所有三个字段。我只想要名字。

func getUserProfile() {
    let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name"], tokenString: accessToken?.tokenString, version: nil, httpMethod: "GET")
    req?.start(completionHandler: { (connection, result, error : Error!) -> Void in
        if(error == nil)
        {
            print("\(String(describing: result))")
            self.FBUserName.text = "name \(String(describing: result))"
        }
        else
        {
            print("error \(String(describing: error))")
        }
    })
}

标签: swiftfacebook-graph-api

解决方案


您可以将结果转换为[String : Any],像这样

if error != nil {
    print("Error: \(error!.localizedDescription)")
} else if let result = result as? [String : Any] {
    self.FBUserName.text = result["name"] as! String
}

这是我的工作要求

let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email,name"])
graphRequest.start(completionHandler: { [weak self] (connection, result, error) -> Void in
    if error != nil {
        print("Error: \(error!.localizedDescription)")
    } else if let result = result as? [String : Any], let strongSelf = self {
        strongSelf.txtName.text = (result["name"] as! String)
        strongSelf.txtEmail.text = (result["email"] as! String)
    }
})

推荐阅读