ios - Swift - 在 applicationWillTerminate 中调用本地通知方法
<p><p>我有一个用于本地通知的公共(public)函数,我想在 applicationWillTerminate 中调用该函数。当我尝试这个时,没有任何反应。我确定本地通知功能没问题,因为当我在 viewDidLoad 中调用它时,它可以正常工作。</p>
<hr/>
<p>这是本地通知功能;</p>
<pre><code>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
}
}
</code></pre>
<p>AppDelegate;</p>
<pre><code>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:.
}
</code></pre>
<p>我在 SO 中搜索了类似的问题,发现了 2 个问题,但没有一个能解决我的问题。</p>
<p> <a href="https://stackoverflow.com/questions/35435161/send-local-notification-after-termination-app-swift-2" rel="noreferrer noopener nofollow">Send local notification after termination app swift 2</a> </p>
<p> <a href="https://stackoverflow.com/questions/17988245/local-notification-on-application-termination" rel="noreferrer noopener nofollow">Local notification on application termination</a> </p>
<hr/>
<p>编辑:请求授权;</p>
<pre><code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: ?) -> 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
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您链接到的第二个问题的答案似乎相关 - 如果系统决定在后台终止您的应用程序,则不能保证调用 <code>applicationWillTerminate</code>。</p></p>
<p style="font-size: 20px;">关于ios - Swift - 在 applicationWillTerminate 中调用本地通知方法,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/42235023/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/42235023/
</a>
</p>
页:
[1]