变量值在 fbsdk 图形请求后变为 nil



我正在用swift编写一个项目,我对这门语言很陌生。

我将变量"用户名"的值设置为我向 facebook sdk 请求的结果,但我的变量值在图形请求后变为 nil。变量赋值在图形请求本身中工作正常。

这是我的代码。

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
class SecondViewController: UIViewController {
var username : String = "X"
let label = UILabel()

override func viewDidLoad() {
super.viewDidLoad()
FBSDKGraphRequest(graphPath: "/me", parameters: ["Fields" : "name"]).start {
(connection, result, err) in
if err != nil {
print("Failed to start request", err)
return
}
var res = result as? [String : Any]
self.username = (res?["name"] as! String)
print(self.username)

}

print(self.username)
}
}

请求内的第一个 print 语句工作正常,但请求外部的第二个 print 语句打印空行。

当我想将标签的文本设置为用户名变量的值时,情况也是如此。它在请求中工作,但没有做任何其他事情。

我认为首先执行登录哪些权限:

loginManager.logIn(withReadPermissions: ["email","public_profile"], from: self) { (FBSDKLoginManagerLoginResult, Error) in
if(Error == nil){
if(FBSDKLoginManagerLoginResult?.isCancelled)!{
SVProgressHUD.showError(withStatus: "You Cancelled To Login With Facebook, n Try Again Later!")
}else if(FBSDKLoginManagerLoginResult?.token != nil){
SVProgressHUD.showSuccess(withStatus: "Login Successfull")
SVProgressHUD.show(withStatus: loadingText)
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
let resultDic = result as! [String: Any]
let facebookProfileUrl : String! = "http://graph.facebook.com/((FBSDKLoginManagerLoginResult?.token!.userID)!)/picture?type=large"
var fbId = (FBSDKLoginManagerLoginResult?.token!.userID)! as String
var name = resultDic["name"] as! String      
var email = resultDic["email"] as! String
}else{
print(error!.localizedDescription)
}
})
}
}
}
}

由于您的内部代码正在工作,这意味着您在上面表现良好,我认为它在线程中工作,这意味着首先打印您的底部"print(self.username)",然后在块内部的上方打印,

可以在图形 API 响应完成后对其进行记录。

最新更新