使用swift 3.1在Xcode8.3上运行它
以下是我在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的Debug区域获取消息。
==== didReceiveRemoteNotification ====
[AnyHashable("id"): 123, AnyHashable("aps"): {
alert = "Hello World \U270c";
badge = 3;
}]
但是,我的iPhone上没有收到任何通知。
我错过了什么吗?
答案 0 :(得分:1)
如果你想处理通知,当你的应用处于活动状态时,你应该这样做,因为推送视图不会出现
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if application.applicationState == .active {
//create custom view or something
} else {
//it was background/off
}
}
答案 1 :(得分:1)
使用 iOS 10 ,您可以执行以下操作,以便在App位于Foreground时查看推送通知。您必须在AppDelegate中实现以下功能。这是 UNUserNotificationCenterDelegate 的委托方法。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
按照以下步骤操作:
let center = UNUserNotificationCenter.current()
center.delegate = self
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert,.badge,.sound]) }
现在,如果您推送,即使您的应用处于前台,也可以看到通知提醒。 More Info in Apple Doc