หากต้องการรัน Timer ใน Background Apple มีเมธอด beginBackgroundTaskWithExpirationHandler อ่านรายละเอียด
ขั้นตอนที่ 1: สร้างโปรเจกต์
Xcode → Single View Application → ชื่อ "BackgroundTimer"
ขั้นตอนที่ 2: เขียนโค้ดใน AppDelegate
ใน applicationDidEnterBackground:
func applicationDidEnterBackground(_ application: UIApplication) {
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
_ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)
}ขั้นตอนที่ 3: สร้างฟังก์ชัน doSomething
@objc func doSomething() {
print("I'm running")
}โค้ดเต็ม
func applicationDidEnterBackground(_ application: UIApplication) {
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
_ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)
}
@objc func doSomething() {
print("I'm running")
}ทดสอบ
รันแอป กด Home เพื่อส่งแอปไป Background จะเห็น "I'm running" พิมพ์ใน Console ทุก 1 วินาที
ข้อจำกัด: iOS อนุญาตให้รัน Background ได้สูงสุด ~3 นาที (ตามเอกสาร Apple) หลังจากนั้น Timer จะหยุด เมื่อนำแอปกลับ Foreground Timer จะทำงานต่อ
