【发布时间】:2017-02-14 19:54:12
【问题描述】:
我有一个用于本地通知的公共函数,我想在 applicationWillTerminate 中调用该函数。当我尝试这个时,没有任何反应。我确定本地通知功能没问题,因为当我在 viewDidLoad 中调用它时,它可以正常工作。
这是本地通知功能;
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
编辑:请求授权;
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 按两次按钮并删除该应用程序。我也在使用真机进行测试。
-
您是否在代码的前面某处
requestAuthorization(options:completionHandler:)? -
This solution 是一个 hack,但它对我有用。它的要点是应用程序在可以安排通知之前被终止。 hack 的作者所做的就是让线程休眠。
标签: ios swift uilocalnotification unusernotificationcenter