Michal
Michal

Reputation: 162

Swift wait asynchronous return

I use Facebook API in swift and I want to catch when the asynchronous function FBSDKGraphRequest results are ready.

I use this function to return data from Facebook

func returnUserData()
{
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            println("Error: \(error)")
        }
        else
        {
            let userName : String = result.valueForKey("name") as! String
            self.userFB = userName
        }
    })
}

Upvotes: 2

Views: 3476

Answers (1)

VBaarathi
VBaarathi

Reputation: 803

If you google around you will find many examples of completion handler and closures. The following is a simple modification of your code to return the result on completion.

func returnUserData(completion:(result:String)->Void)
{
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

    if ((error) != nil)
    {
        // Process error
        println("Error: \(error)")
    }
    else
    {
        let userName : String = result.valueForKey("name") as! String
        completion(result:userName)
    }
})
}

Now in your main code you call this function like the following:

returnUserData({(result)->Void in 
  self.userFB = result
  //CONTINUE RUNNING THE APP WITH OTHER METHODS OR FUNCTIONS
  continueDoingSomething()
})

So what you are doing is, you are will only continue other actions in your app after you get the FB user id without really freezing the main thread in the back. There are many efficient ways to do this, googling and reading about this topic will help.

Upvotes: 3

Related Questions