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

标签 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 秒执行一次代码块的后台任务以及如何停止该任务?

最佳答案

结合 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方法同上。

关于objective-c - 在 Swift 中将后台任务作为循环运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29561476/

相关文章:

objective-c - -[__NSCFDictionary JSONRepresentation] : unrecognized selector

iphone - 在尝试将 ios 应用程序发布到应用程序商店之前需要完成的事情

iphone - ScrollView 一次只滚动一项

ios - 删除 iOS 应用设置

swift - 是否可以为 RealityKit 中的对象设置基于位置的 anchor ?

iphone - 调用类别方法时发送到实例的无法识别的选择器

ios - 在 UIView 中逐像素绘制像素

iphone - Xcode 4.2 - 证书正常,但出现 "There is no codesign_wrapper executable. Please reinstall the Xcode developer tools."

iphone - 我为使用 makefile 构建的 iO 寻找库项目

ios - 强制 SFSafariViewController 加载网站的桌面版本