在 Swift 2 中创建异步任务

Creating ASYNC task in Swift 2

我想在地图上向用户显示当前位置,我知道这不是即时任务。我想在 ASYNC 任务中调用我的 showCurrentLocation() 函数。我试图学习回调闭包,但我无法理解如何为此创建 ASYNC 任务。我知道这不是 Whosebug 的最佳问题模板,但我不知道如何提出不同的问题。 感谢您的任何帮助。 祝你编码愉快。

有一种称为 GCD (Grand Central Dispatch) 的技术,您可以使用它来执行此类任务。

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
    // do some task
    dispatch_async(dispatch_get_main_queue()) {
        // update some UI
    }
}

过去我制作了一个名为 AsyncTask 的 class 用于像您在此处描述的那样的使用目的。

最近我更新了 swift 3

它有 2 个通用类型:

BGParam - 执行时发送给任务的参数类型。

BGResult - 后台计算结果的类型。

如果不需要其中之一(或两者),您可以将其设置为可选或忽略。

在代码示例中,我引用了您在 OP 和评论中提到的函数 showCurrentLocation() & getCurrentLocation()BGParam 设置为 Int & BGResults 设置为 CLLocationCoordinate2D

AsyncTask(backgroundTask: {(param:Int)->CLLocationCoordinate2D in
        print(param);//prints the Int value passed from .execute(1)
        return self.getCurrentLocation();//the function you mentioned in comment
        }, afterTask: {(coords)in
            //use latitude & longitude at UI-Main thread
            print("latitude: \(coords.latitude)");
            print("latitude: \(coords.longitude)");
            self.showCurrentLocation(coords);//function you mentioned in OP
    }).execute(1);//pass Int value 1 to backgroundTask