emresancaktar
emresancaktar

Reputation: 1567

Creating ASYNC task in Swift 2

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.

Upvotes: 3

Views: 6141

Answers (2)

Nikita Kurtin
Nikita Kurtin

Reputation: 6237

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

Upvotes: 5

Shripada
Shripada

Reputation: 6514

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

Upvotes: 4

Related Questions