My device is not receiving background push notifications. I'm at wits end, I've tried every tutorial I can find and searched through Stack Overflow.
- Device and APN are set to debug/development
- I can successfully register device token
- I have an active .p8 key with push notification services
- APN says the push message was sent successfully
- didReceiveRemoteNotification doesn't fire
- Tried with app in background and foreground
- using AWS: inbound - port 22, outbound - all ports
This is the response:
{"sent":[{"device":"cc7ec9a821cf232f9510193ca3ffe7d13dd756351794df3f3e44f9112c037c2a"}],"failed":[]}
Here is my code:
AppDelegate.swift
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var deviceTokenString: String = ""
for i in 0..<deviceToken.count {
deviceTokenString += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
UserDefaults.standard.set(deviceTokenString, forKey: "push_token")
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
print("\(notification.request.content.userInfo)")
completionHandler([.alert, .badge, .sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Handle push from background or closed")
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("\(response.notification.request.content.userInfo)")
completionHandler()
}
}
XCode:
Node.js
.p8 key is from Developer Console: Keys > All
var apn = require('apn');
var apnProvider = new apn.Provider({
token: {
key: "/path/to/AuthKey_1234ABCD.p8",
keyId: "1234ABCD",
teamId: "1234ABCD"
},
production: false
});
var note = new apn.Notification();
note.topic = "com.company.app";
note.payload = {
aps: {
"content-available" : 1
},
custom_field: {}
};
apnProvider.send(note, push_token).then(result => {
console.log('result: ', result);
console.log("sent:", result.sent.length);
console.log("failed:", result.failed.length);
});

