在 iOS 10.2 中本地通知不会出现

Local notification is not coming in forgeound in iOS 10.2

我已经为 iOS 10.2 成功实现了本地通知。

但问题是只有当应用程序在后台时才会出现通知警报如果应用程序在前台则不会出现警报。

是否可以在前台获取本地通知?

我的代码在这里

func notificationNow(){

        print("notification will be triggered in five seconds..Hold on tight")
        let content = UNMutableNotificationContent()
        content.title = "Intro to Notifications"
        content.subtitle = "Lets code,Talk is cheap"
        content.body = "Sample code from WWDC"
        content.sound = UNNotificationSound.default()

        //To Present image in notification
        if let path = Bundle.main.path(forResource: "menu2", ofType: "png") {
            let url = URL(fileURLWithPath: path)

            do {
                let attachment = try UNNotificationAttachment(identifier: "sampleImage", url: url, options: nil)
                content.attachments = [attachment]
            } catch {
                print("attachment not found.")
            }
        }

        // Deliver the notification in five seconds.
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5.0, repeats: false)
        let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: trigger)

        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().add(request){(error) in

            if (error != nil){
                print(error?.localizedDescription as Any)
            }
        }
    }

当应用 运行 在前台时。您需要通过委托方法捕获本地通知。

因此,在您的 AppDelegate 中实施 didFinishLaunchingWithOptions 方法中的委托侦听:

在您的应用完成启动之前设置代理很重要。

// Do NOT forget to retain your delegate somewhere
let notificationDelegate = UYLNotificationDelegate()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  let center = UNUserNotificationCenter.current()
  center.delegate = notificationDelegate

  // ...
  return true
}

如果您想在您的应用程序处于前台时响应可操作的通知或接收通知,您需要实施 UNUserNotificationCenterDelegate。该协议定义了两个可选方法:

  • userNotificationCenter(_:willPresent:withCompletionHandler:)
    当通知传送到前台应用 时调用。你
    接收包含原始
    UNNotification 对象 UNNotificationRequest。您使用
    调用完成处理程序 UNNotificationPresentationOptions 你想展示(使用 .none 到
    忽略警报)。

  • userNotificationCenter(_:didReceive:withCompletionHandler:) 被调用 当 用户在发送的通知中选择一个操作时 。你 接收 UNNotificationResponse 对象,其中包括 用户操作的 actionIdentifier 和 UNNotification 对象。 系统定义的标识符 UNNotificationDefaultActionIdentifierUNNotificationDismissActionIdentifier 在用户点击时使用 打开应用程序的通知或滑动以关闭 通知。

在这两种情况下,您都必须在完成后调用完成处理程序。

#pragma mark - UNUserNotificationCenterDelegate Methods

func userNotificationCenter(_ center: UNUserNotificationCenter,
   willPresent notification: UNNotification, 
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Play sound and show alert to the user
     completionHandler([.alert,.sound])
}

使用以下方法将通知配置为在前台显示,

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

详情可参考Apple documentation

在class你想观察本地通知的地方写下面的代码(扩展名)

当您在前台收到通知或用户在应用程序处于后台时点击通知时,这将发出通知。

希望这能解决您的问题。

extension ViewController:UNUserNotificationCenterDelegate{


func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    print("Tapped in notification")
}

//This is key callback to present notification while the app is in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    print("Notification being triggered")
    //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
    //to distinguish between notifications
//        if notification.request.identifier == requestIdentifier
//        {

        completionHandler( [.alert,.sound,.badge])

//        }
       }

}

UNUserNotificationCenterDelegate 的文档中:

Important

You must assign your delegate object to the UNUserNotificationCenter object no later before your app finishes launching. For example, in an iOS app, you must assign it in the application(:willFinishLaunchingWithOptions:) or application(:didFinishLaunchingWithOptions:) method.

您似乎在很久以后才设置代理 — 就在通知添加到通知中心之前。

我创建了一个简单的 Swift class 单例,带有符合 UNUserNotificationCenterDelegate 的扩展。在单例的 init 方法中,我将委托分配给了自己。然后我在 AppDelegate 的 willFinishLaunchingWithOptions 方法中初始化单例。