У меня есть публичная функция для локального уведомления, и я хочу вызвать эту функцию в applicationWillTerminate. Когда я пытаюсь это сделать, ничего не происходит. Я уверен, что функция локального уведомления в порядке, потому что, когда я вызываю это в viewDidLoad, он работает правильно.Swift - вызов метода локального уведомления в приложенииWillTerminate
Это функция для местного уведомления;
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:.
}
Я искал SO для подобных проблем и нашел 2 вопроса, но ни один из них не решил мою проблему.
Send local notification after termination app swift 2
Local notification on application termination
Edit: Запрос авторизации;
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: completeHandler:)' где-то раньше в вашем коде? – rmp