在Swift 2中创建ASYNC任务

emr*_*tar 3 closures asynchronous callback ios swift

我想在地图中向用户显示当前位置,我知道这不是即时任务.我想在ASYNC任务中调用我的showCurrentLocation()函数.我试图学习回调闭包,但我无法理解如何为此创建ASYNC任务.我知道这不是stackoverflow的最佳问题模板,但我不知道我怎么能有不同的问题.感谢您的任何帮助.有一个很好的编码.

Nik*_*tin 5

在过去,我已经创建了一个名为AsyncTask的类,用于此处描述的用法目的.

最近我为swift 3更新了它

它有2种通用类型:

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

BGResult - 背景计算结果的类型.

如果不需要其中一个(或两个),您可以将其设置为Optional或忽略.

在代码示例我指的功能,showCurrentLocation()getCurrentLocation()你在OP&评论提及. 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
Run Code Online (Sandbox Code Playgroud)