在Swift中将后台任务作为循环运行

时间:2015-04-10 12:29:25

标签: objective-c iphone swift

我知道我可以创建这样的后台任务:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // do some task
    dispatch_async(dispatch_get_main_queue(), ^{
        // update some UI
    });
});

Source

如何创建每n秒执行代码块的后台任务,如何停止此任务?

1 个答案:

答案 0 :(得分:16)

合并NSTimer和您的背景代码。那将是:


的Objective-C

- (void)someBackgroundTask:(NSTimer *)timer {
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),
   ^{
      // do some task
      dispatch_async(dispatch_get_main_queue(), ^{
        // update some UI
      });
  });
}

然后通过计时器

调用此方法
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 
                                         target:self 
                                       selector:@selector(someBackgroundTask:)
                                       userInfo:nil
                                        repeats:YES];

停止该计时器和后台执行

[timer invalidate];


Swift 2.2

func someBackgroundTask(timer:NSTimer) {
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), 
     { () -> Void in

        println("do some background task")

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            println("update some UI")

        })
    })
}

然后通过计时器

调用此方法
var timer = NSTimer(timeInterval: 1.0, 
                          target: self, 
                        selector: "someBackgroundTask:",
                        userInfo: nil, 
                         repeats: true)

停止该计时器和后台执行

timer.invalidate()

Swift 3及更高版本

func someBackgroundTask(timer:Timer) {
    DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
        print("do some background task")

        DispatchQueue.main.async {
            print("update some UI")
        }
    }
}

并创建/调用计时器为

var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { 
              timer in

              self.someBackgroundTask(timer: timer)
            }

invalidate方法相同。