我結束了創建一個小班,以確定當應用程序已經進入暫停狀態:
class SuspendedMonitor {
static let shared = SuspendedMonitor()
var delegate: SuspendedMonitorDelegate?
private let Interval = 10.0
private let MaxDelta = 2.0
private var _timestamp: Double
private var _timer: Timer?
private init() {
_timestamp = timeInMs()
}
public func start() {
_timestamp = timeInMs()
NotificationCenter.default.addObserver(
self,
selector: #selector(enterForeground),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(enterBackground),
name: NSNotification.Name.UIApplicationDidEnterBackground,
object: nil
)
}
@objc func enterForeground() {
checkSync()
_timer?.invalidate()
}
@objc func enterBackground() {
_timestamp = timeInMs()
setupTimer()
}
@objc func incrementTime() {
_timestamp = _timestamp + (Interval * 1000)
}
private func setupTimer() {
_timer = Timer.scheduledTimer(
timeInterval: Interval,
target: self,
selector: #selector(incrementTime),
userInfo: nil,
repeats: true
)
}
private func checkSync() {
if timeInMs() - _timestamp > ((Interval + MaxDelta) * 1000) { appSuspended() }
}
private func appSuspended() {
delegate?.appDidSuspend(self)
}
}
protocol SuspendedMonitorDelegate: class {
func appDidSuspend(_ monitor: SuspendedMonitor)
}
你似乎已經在這裏想到的東西,很可能將是不可能的,因爲沒有委託方法通知您從後臺到暫停的狀態轉換。文檔明確表示您應該「準備暫停」。與其試圖專注於此,我會尋找一種方法來防止由於連接問題或延遲而離開後臺狀態,並相應地調整問題。 :)如果這是一個不夠快的下載任務,請嘗試調整它,讓這裏的人知道你做了什麼以及如何停止(導致操作系統認爲你完成並暫停你)。 – Gero