我已经实施了本地和远程通知,当app处于后台时,这两种通知都有效。用户将点击任何通知,一切正常。
但当应用处于前台模式时。当应用收到远程通知时, didReceiveRemoteNotification 委托不会自动触发。在这种情况下,用户需要进行交互/点击通知,但我希望应用程序无需用户交互即可检测到。
以下是我用于安排本地通知的代码。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
}
但如果在行上方评论,应用程序将开始检测远程通知而无需用户在前台进行交互。但我需要本地通知的这种行为。
下面是我的didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
ScheduleLocalNotifications().scheduleNotification()
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
UIApplication.shared.applicationIconBadgeNumber = 0
application.registerForRemoteNotifications()
Fabric.with([Crashlytics.self])
return true
}
//远程通知处理
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let jsonResult = userInfo["aps"] as! Dictionary<String, AnyObject>
print(jsonResult["alert"] ?? "Not Found")
}
//本地通知处理
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
}