Creating ASYNC task in Swift 2

2019-05-10 00:03发布

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.

2条回答
我想做一个坏孩纸
2楼-- · 2019-05-10 00:17

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
查看更多
聊天终结者
3楼-- · 2019-05-10 00:21

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
    }
}
查看更多
登录 后发表回答