Search code examples
iosswiftnotificationscloudcloudkit

Receiving a Remote Notification in Swift 3


I have the following code:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    let queryNotification = CKQueryNotification(fromRemoteNotificationDictionary: userInfo)
    let notification = Notification(name: NSNotification.Name("Name"), object: nil, userInfo: ["Key": queryNotification])
    NotificationCenter.default.post(notification)
}

However, I was told that this is not the right way to receive remote notifications. Instead, I was directed to use the following delegate method. I don't see how this method can be used to do what I did above. Somebody please help.

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

Solution

  • I think what you're trying to do is something like this:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
        // Extrapolate userInfo
        let userInfo = response.notification.request.content.userInfo
        let queryNotification = CKQueryNotification(fromRemoteNotificationDictionary: userInfo)
        let notification = Notification(name: NSNotification.Name("Name"), object: nil, userInfo: ["Key": queryNotification])
        NotificationCenter.default.post(notification)
    
        completionHandler()
    }