我不確定這是不可能的,或者如果我錯誤地實現它。處於非活動應用程序狀態的本地通知
我試圖完成使用beginBackgroundTask
(expirationHandler
),然後張貼LocalNotification
一旦完成對iOS10
在後臺任務。問題在於Notification
不會一直觸發 - 我可以設置breakpoint
以使用presentLocalNotificationNow
來查看它,但它並不總是顯示給用戶,並且只有當應用程序返回到(通過從主屏幕打開它) didReceiveLocalNotification
被調用。
如果我在調度通知時檢查應用程序狀態,它的rawValue是2,我認爲它是不活動的,所以我假設這是它沒有向用戶傳遞通知的原因。
我已經嘗試在任務完成後安排notification
5秒,然後立即調用endBackgroundTask
,但通知仍然不會一直顯示給用戶。 EndBackgroundTask
不會被調用,我認爲應該將應用程序從非活動狀態移動到notification
應該顯示的背景,但我假設它不是立即執行,並且在實際發生時由系統自行決定。
我在做什麼錯?
相關的代碼是:
let task = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
// Long running task
let notification = UILocalNotification()
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertBody = "Message"
let settings = UIUserNotificationSettings(types: [.alert, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.presentLocalNotificationNow(notification)
UIApplication.shared.endBackgroundTask(task)