2015-08-24 36 views
2

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

+1

看看的NSOperation http://nshipster.com/nsoperation/ – msg

+0

谢谢。我会看看NSOperation – emresancaktar

回答

5

在过去,我已经有了一个为使用目的,如你在这里所描述的一个叫AsyncTask类。 - 在执行时发送给任务的参数的类型

BGParam

最近我一直为迅速3

它有2种泛型类型更新它。

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

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

在代码示例中,我指的是您在OP &评论中提到的功能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 
4

有一种叫做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 
    } 
} 
+0

首先感谢你的回答。我知道GCD。我想知道,我可以用闭包创建自定义异步任务吗?想想这种情况。 让我们假设我们有一个getCurrentLocation()函数,它返回我们userCurrentLocation.latitude和longitude。我无法即时获取值,所以我必须使用回调机制。它应该告诉我,我们发现的位置,并有结果,所以我可以在主线程中使用它们。如果您将getCurrentLocation函数放在后台线程中。它解决了我的问题吗?它会像回调机制一样工作吗?谢谢 ! – emresancaktar

+0

使用全局队列不是最好的主意......你更新知道谁在使用它。创建自己的并发队列是一个更好的解决方案。 – user3441734