【问题标题】:Swift - Background Fetch and DelaySwift - 后台获取和延迟
【发布时间】:2017-06-12 08:56:00
【问题描述】:

我在我的应用中实现了后台获取功能。

后台获取调用的函数包含一个延迟函数。

但是这个函数似乎没有触发:

let when = DispatchTime.now() + 2 
DispatchQueue.main.asyncAfter(deadline: when) {
    MyFunction()
}

它似乎在我唤醒应用程序后立即触发。

为什么这不会在后台获取时触发?

【问题讨论】:

  • 如果这应该是延迟等待某事已经完成,不要那样做。
  • 预期结果是什么?等待(延迟)然后执行MyFunction() 还是相反?
  • 哦,是的,我应该提到我知道这是一种糟糕的做法,但在我的情况下仍然足够好 :)
  • @AhmadF 是的,等待 x 秒然后执行 MyFunction 是预期的结果。

标签: ios swift xcode swift3


【解决方案1】:

试试这个代码:

   DispatchQueue.global().async {
        let timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.MyFunction), userInfo: nil, repeats: false)
        RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
        RunLoop.current.run()
    }

【讨论】:

    【解决方案2】:

    我认为您不能在主队列的后台运行。试试这个(将main 更改为global()):

    let when = DispatchTime.now() + 2 
    DispatchQueue.global().asyncAfter(deadline: when) {
        MyFunction()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2018-01-20
      相关资源
      最近更新 更多