在 Xcode8.3 和 swift 3.1 上运行它
下面是我在 AppDelegate.swift 中的代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
if granted {
print("OK!")
}
else {
print("No!")
}
})
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("==== didReceiveRemoteNotification ====")
print(userInfo)
}
我使用 node-apns 将通知推送到我的应用程序,并且我可以从 Xcode 中的调试区域收到消息。
==== didReceiveRemoteNotification ====
[AnyHashable("id"): 123, AnyHashable("aps"): {
alert = "Hello World \U270c";
badge = 3;
}]
但是,我的 iPhone 上没有收到任何通知。
我错过了什么吗?
最佳答案
使用iOS 10,您可以执行以下操作以在应用程序处于前台时查看推送通知。您必须在 AppDelegate 中实现以下功能。它是UNUserNotificationCenterDelegate的委托(delegate)方法。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
请按照以下步骤操作:
- 导入UserNotifications并在AppDelegate中扩展UNUserNotificationCenterDelegate。
- 在 didFinishLaunchingWithOptions 中设置 UNUserNotificationCenter 委托(delegate)。
let center = UNUserNotificationCenter.current()
center.delegate = self
- 在 AppDelegate 中实现 will Present 方法,并使用选项调用完成处理程序。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert,.badge,.sound]) }
现在,如果您收到推送,即使您的应用程序位于前台,您也可以看到通知警报。 More Info in Apple Doc .
关于ios - 为什么我的 iPhone 上没有收到任何通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43407419/