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

标签 ios iphone swift xcode

在 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)

请按照以下步骤操作:

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

enter image description here

  • 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/

    相关文章:

    ios - CoreData ValueTransformer.transformedValueClass() 在 Swift 3 中从未被调用

    ios - 设置动态 UILabel 高度

    ios - UIImagePickerController 覆盖按钮未触发

    ios - UIView 在呈现其他 View Controller 后重置为初始值

    iphone - ios:在 UIButton 中以编程方式编辑的内容居中

    ios - 从 Swift 中的字符串中提取整个单词

    ios - 将 Game over 实现到 swift 游戏中

    iphone - 如何将 UILabel View 更改为 UIImageView Xcode,Iphone

    javascript - 如何使用 Javascript 在 Safari HTML5 播放器中使用 iOS 锁屏上一个/下一个播放器按钮

    ios - 如何使用 Core Graphics 右对齐文本