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

时间:2017-04-14 07:48:34

标签: ios iphone swift xcode

使用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上没有收到任何通知。

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

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

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

您可能也有兴趣创建新的构建架构,因此您的应用会等到它启动,因此您可以在接收推送时调试应用行为。enter image description here enter image description here

答案 1 :(得分:1)

使用 iOS 10 ,您可以执行以下操作,以便在App位于Foreground时查看推送通知。您必须在AppDelegate中实现以下功能。这是 UNUserNotificationCenterDelegate 的委托方法。

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

按照以下步骤操作:

  1. 导入 UserNotifications 并在AppDelegate中扩展 UNUserNotificationCenterDelegate
  2. enter image description here

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

        现在,如果您推送,即使您的应用处于前台,也可以看到通知提醒。 More Info in Apple Doc