Creating ASYNC task in Swift 2

主宰稳场 提交于 2019-12-07 16:23:14

问题


I want to show users current location in map and I know it's not instantaneous task. I want to call my showCurrentLocation() function in the ASYNC task. I was trying to learn call back closures but i could not understand how can I create ASYNC task for this. I know this is not a best question template for stackoverflow but I don't know how can I ask differently. Thank you for any help. Have a nice coding.


回答1:


In the past I've made a class called AsyncTask for usage purposes like the one you described here.

Lately I've updated it for swift 3

It has 2 generic types:

BGParam - the type of the parameter sent to the task upon execution.

BGResult - the type of the result of the background computation.

If one of them(or both) isn't needed you can set it to Optional or just ignore.

In code example I refer the functions showCurrentLocation() & getCurrentLocation() that you mentioned in OP & comments. BGParam is set to Int & BGResults is set to 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:


There is a technology called GCD (Grand Central Dispatch) which you can use to perform such tasks.

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
    }
}


来源:https://stackoverflow.com/questions/32177362/creating-async-task-in-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!