为什么我没有收到我的iPhone通知?

在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中的“debugging”区域获取消息。

 ==== didReceiveRemoteNotification ==== [AnyHashable("id"): 123, AnyHashable("aps"): { alert = "Hello World \U270c"; badge = 3; }] 

但是,我没有收到我的iPhone上的任何通知。

我错过了什么吗?

如果你想处理通知,当你的应用程序处于活动状态时,应该这样做,因为推送视图不会出现

 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { if application.applicationState == .active { //create custom view or something } else { //it was background/off } } 

你可能也有兴趣创build新的构build模式,所以你的应用程序将等待,直到它启动,所以你可以debugging你的应用程序的行为,当接收推。 在这里输入图像说明 在这里输入图像说明

使用iOS 10时 ,您可以执行以下操作,以在App处于前台时查看推送通知。 你必须在AppDelegate中实现下面的function。 这是UNUserNotificationCenterDelegate的委托方法。

  func userNotificationCenter(_ center:UNUserNotificationCenter,willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - > Void) 

按照以下步骤操作:

  1. 导入UserNotifications并在AppDelegate中扩展UNUserNotificationCenterDelegate

在这里输入图像说明

  1. didFinishLaunchingWithOptions中设置UNUserNotificationCenter委托。
 让中心= UNUserNotificationCenter.current() 
center.delegate = self
  1. 在AppDelegate中实现will present方法,并使用选项调用完成处理程序。
  func userNotificationCenter(_ center:UNUserNotificationCenter,willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - > Void){
         completionHandler([警报,.badge,.sound])
 } 

现在,如果您获得推送,即使您的应用处于前台,您也可以看到通知提醒。 更多信息在Apple Doc 。