我一直在浏览各种Apple API文档,但对于使用哪种方法来检测是否在后台和前台从我的应用程序中发送了通知,我没有找到明确的答案。具体来说,我想在收到另一个通知后立即安排新的通知。使用Swift 4,但欢迎使用Objective-C解决方案
答案 0 :(得分:0)
确保内容可用:有效负载中有1个可用于后台通知,这里是
// Push notification received
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Error = ", error.localizedDescription)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let state = application.applicationState
DispatchQueue.main.async { // active
if state == .active {
PushManager.object().handlePushNotification(userInfo, isCameFromForeground: true)
} else if state == .background {
PushManager.object().handlePushNotification(userInfo)
} else {
PushManager.object().handlePushNotification(userInfo)
}
}
completionHandler(.newData)
}
// Notification handling for iOS 10
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let data = notification.request.content.userInfo
let state = UIApplication.shared.applicationState
DispatchQueue.main.async { // active
if state == .active {
PushManager.object().handlePushNotification(data, isCameFromForeground: true)
} else if state == .background {
PushManager.object().handlePushNotification(data)
} else {
PushManager.object().handlePushNotification(data)
}
}
completionHandler([.alert, .badge, .sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let data = response.notification.request.content.userInfo
let state = UIApplication.shared.applicationState
DispatchQueue.main.async { // active
if state == .active {
PushManager.object().handlePushNotification(data, isCameFromForeground: true)
} else if state == .background {
PushManager.object().handlePushNotification(data)
} else {
PushManager.object().handlePushNotification(data)
}
}
completionHandler()
}
答案 1 :(得分:0)
谢谢您的回答。发布此内容以帮助他人。
为了实现后台通知处理,您必须使用全局变量的高级编程概念(在Swift 4中引入)
//in ViewController.swift
var showNotificationsInBackground : Bool = true
这就是您要做的所有事情!感谢您的时间和15分! :)
答案 2 :(得分:-1)
您需要在您的应用中添加“ Notification Service Extension”。然后遵循get delivery of push notification。在这种情况下,您可以响应服务器有关推送通知的传递的信息,并可以安排另一个推送通知。