等待函数在Swift中结束

时间:2015-04-20 09:30:56

标签: ios swift

我有一个使用json获取数据的函数,我将所有数据附加到数组中。我尝试创建信号量并等到发送信号到信号量继续但它不起作用(我不确定我是否正确),然后我在Stackoverflow中看到一个问题,答案是创建一个完成处理程序像那样

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    getUrunGrup(completionHandler)
}

所以我改变了我的功能

func getUrunGrup(completionHandler: ((UIBackgroundFetchResult) -> Void)!){
    Alamofire.request(.GET, "http://213.136.86.160:27701/Thunder/DataService/GetUrunGrup")
        .responseJSON {(request, response, jsonObj, error) in
            if let jsonresult:NSDictionary = jsonObj as? NSDictionary{
                if let result: AnyObject = jsonresult["Result"] {
                    let elementCount = result.count
                    for (var i = 0; i<elementCount; ++i){
                        if let name: AnyObject = result[i]["Adi"]!{
                            if let kod:AnyObject = result[i]["Kod"]!{
                                urunUstGrup.append(["Adi": "\(name)", "Kod": "\(kod)"])
                                println("getUrunGrup \(i)")


                                }
                            }
                        }
                    }
                }

            }
    completionHandler(UIBackgroundFetchResult.NewData)
    println("Background Fetch Complete")

    }

但我怎么称呼这个功能没有答案?

1 个答案:

答案 0 :(得分:2)

你必须将你的异步函数传递给稍后调用的处理程序,如下所示:

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    loadShows(completionHandler)
}

func loadShows(completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    //....
    //DO IT
    //....

    completionHandler(UIBackgroundFetchResult.NewData)
    println("Background Fetch Complete")
}

或(清洁方式恕我直言)

添加一个中间completionHandler

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    loadShows() {
        completionHandler(UIBackgroundFetchResult.NewData)
        println("Background Fetch Complete")
    }
}

func loadShows(completionHandler: (() -> Void)!) {
    //....
    //DO IT
    //....
    completionHandler()
}