我有一個用於本地通知的公共函數,我想在applicationWillTerminate中調用該函數。當我嘗試這個時,沒有任何反應。我確定本地通知功能是可以的,因爲當我在viewDidLoad中調用它時,它可以正常工作。Swift - 在applicationWillTerminate中調用本地通知方法
這是本地通知的功能;
func scheduleLocalNotification(second: Double) {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.badge = 1
content.title = "Title!"
content.body = "Message!"
content.categoryIdentifier = "id"
content.userInfo = ["key": "value"]
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: second, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
} else {
// Fallback on earlier versions
}
}
AppDelegate;
func applicationWillTerminate(_ application: UIApplication) {
scheduleLocalNotification(second: 30.0)
print("Terminating!")
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
我搜索了類似的問題,發現2個問題,但沒有一個解決我的問題。
Send local notification after termination app swift 2
Local notification on application termination
編輯:請求授權;
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
if (!launchedBefore) {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Authorization granted!")
} else {
print("Authorization not granted!")
}
}
} else {
let settings = UIUserNotificationSettings(types: [.alert, .badge , .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
UserDefaults.standard.set(true, forKey: "launchedBefore")
}
// Override point for customization after application launch.
return true
}
你是如何終止應用程序來測試這個? – Paulw11
@ Paulw11按了兩次按鈕,擺脫了應用程序。我正在使用真實設備進行測試。 – THO
你的'requestAuthorization(options:completionHandler:)'在代碼的早些時候? – rmp