【问题标题】:Creating ASYNC task in Swift 2在 Swift 2 中创建 ASYNC 任务
【发布时间】:2015-08-24 08:10:21
【问题描述】:

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

【问题讨论】:

标签: ios swift asynchronous callback closures


【解决方案1】:

过去我创建了一个名为 AsyncTask 的类,用于您在此处描述的用途。

最近我为 swift 3

更新了它

它有两种泛型:

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

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

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

在代码示例中,我参考了您在 OP 和 cmets 中提到的函数 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

【讨论】:

    【解决方案2】:

    有一种称为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
        }
    }
    

    【讨论】:

    • 首先感谢您的回答。我知道GCD。我想知道,我可以用闭包创建自定义异步任务吗?想想这种情况。假设我们有一个 getCurrentLocation() 函数,它返回 userCurrentLocation.latitude 和 longitude。我无法立即获取值,所以我必须使用回调机制。它应该告诉我我们找到了位置并且有结果,所以我可以在主线程中使用它们。如果将 getCurrentLocation 函数放在后台线程中。它解决了我的问题吗?它会像回调机制一样工作吗?谢谢!
    • 使用全局队列并不是最好的主意……你新人知道谁在使用它。在这里创建自己的并发队列是更好的解决方案。
    猜你喜欢
    • 2022-10-06
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    相关资源
    最近更新 更多