APNs Background Notification Handling

Hi all,

As part of development for my app I'm wanting to utilise the Apple Push Notification service. For now, I have implemented the necessary code in an app delegate class which you can see below

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // Request permission to display alerts and play sounds.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
        
        // Set the delegate for the UNUserNotificationCenter
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }

    // MARK: - APNs Registration

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
        let token = tokenParts.joined()
        print("Device Token: \(token)")
        // Send or save this token as necessary.
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications with error: \(error.localizedDescription)")
    }

    // MARK: - UNUserNotificationCenterDelegate Methods

    // Called when a notification is delivered to a foreground app.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.banner, .sound])
        print("message received!!")
    }

    // Called when a user taps on a notification.
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("user tapped on banner!!")
        completionHandler()
    }
    
    // Called when a notification is delivered in the background
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        if let messageData = userInfo["yourKey"] as? [String: AnyObject] {
            print("Background Notification received!!")
            print(messageData)
            
            completionHandler(.newData)
        } else {
            completionHandler(.noData)
        }
    }
}

To test this, I've just been using the terminal Like so:

curl -v \
     --header "authorization: bearer $JWT" \
     --header "apns-topic: $TOPIC" \
     --header "apns-push-type: alert" \
     --http2 \
     --data '{"aps":{"alert":"Hello from Terminal!", "content-available":1}}' \
     $APNS_ENDPOINT/3/device/$DEVICE_TOKEN

However, despite including the "content-available" tag the didReceiveRemoteNotification function is not being called. Any idea why this is? I have made sure that all the necessary capabilities have been included (background fetch, remote notifications).

Hi Buddy, Im having same issue, did you get any solution ? Appreciate and thank you for your help in advance if any, thanks!! https://forums.developer.apple.com/forums/thread/745188

APNs Background Notification Handling
 
 
Q