Search code examples
swiftvariablesfbsdk

Variable value becomes nil after fbsdk graph request


I am writing a project in swift and I am pretty new to the language.

I set a variable "username"'s value to the result of my request to the facebook sdk, but my variable value becomes nil after the graph request. The variable assignment works fine inside the graph request itself.

Here is my code.

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

}

The first print statement that is inside the request works just fine but the second one that is outside of the request prints an empty line.

This was also the case when I wanted to set the text of a label to the value of the username variable. It worked inside the request but didn't do anything otherwise.


Solution

  • i think first perform login which permissions:

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

    as your inside code is working which means you perform above well, i think its working in threading, which means your bottom "print(self.username)" is printed first, then above one which is inside of block,

    you can LOG it after completion of Graph API response.