简体   繁体   English

Swift等待异步返回

[英]Swift wait asynchronous return

I use Facebook API in swift and I want to catch when the asynchronous function FBSDKGraphRequest results are ready. 我迅速使用了Facebook API,并且想在异步函数FBSDKGraphRequest结果准备好时捕获。

I use this function to return data from Facebook 我使用此功能从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
        }
    })
}

If you google around you will find many examples of completion handler and closures. 如果您在Google周围搜索,则会发现许多完成处理程序和闭包的示例。 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. 因此,您要做的是,只有获得FB用户ID后,您才可以继续执行应用中的其他操作,而不会真正冻结后面的主线程。 There are many efficient ways to do this, googling and reading about this topic will help. 有许多有效的方法可以执行此操作,在Google上搜索和阅读有关此主题的内容将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM