User Notifications

RSS for tag

Push user-facing notifications to the user's device from a server or generate them locally from your app using User Notifications.

Posts under User Notifications tag

149 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

"InvalidProviderToken" with APN push service when using code-generated token
Problem We have successfully set up push notifications using Apple APN service, that is push notifications work when using a token generated using the JSON Web Token Generator in the Push Notification console. However, we get an "InvalidProviderToken" error when creating using our own token using the following code. The Key and TeamID is definitely correct (obviously, censored in the below code). When pasting our token in the JSON Web Token Validator in the Push Notification console we get the error „Invalid signing key“. We merely pasted our secret key in our setNewTokenIfNeeded code, separated on four lines using the “““ style. Does anyone know why this error happens? Given that it works when we upload our .p8 file to the JSON Web Token Generator and we simply paste the text of this file (excluding the lines with "-----BEGIN/END PRIVATE KEY-----") I guess our secret key is correct? Code to generate token fileprivate var currentToken: String? fileprivate var currentTokenCreateTime: Date? fileprivate func setNewTokenIfNeeded() { // Ensure, token is at least 20 minutes but at most 60 minutes old if let currentTokenCreateTime = currentTokenCreateTime { let ageOfTokenInSeconds = abs(Int(currentTokenCreateTime.timeIntervalSinceNow)) NSLog("Age of token: \(Int(ageOfTokenInSeconds / 60)) minutes.") if ageOfTokenInSeconds <= 20 * 60 { return } } // Generate new token NSLog("Renewing token.") let secret = """ ABCABCABCABCABCABCABCABCABCABCABCABC+ABCABC+ABCABCABC+ABCABCAB/+ ABCABCABCABCABCABCABCABCABCABCABCABC+ABCABC+ABCABCABC+ABCABCAB/+ ABCABCABCABCABCABCABCABCABCABCABCABC+ABCABC+ABCABCABC+ABCABCAB/+ ABCABCAB """ let privateKey = SymmetricKey(data: Data(secret.utf8)) let headerJSONData = try! JSONEncoder().encode(Header()) let headerBase64String = headerJSONData.urlSafeBase64EncodedString() let payloadJSONData = try! JSONEncoder().encode(Payload()) let payloadBase64String = payloadJSONData.urlSafeBase64EncodedString() let toSign = Data((headerBase64String + "." + payloadBase64String).utf8) let signature = HMAC<SHA256>.authenticationCode(for: toSign, using: privateKey) let signatureBase64String = Data(signature).urlSafeBase64EncodedString() let token = [headerBase64String, payloadBase64String, signatureBase64String].joined(separator: ".") currentToken = token currentTokenCreateTime = Date() } fileprivate struct Header: Encodable { let alg = "ES256" let kid: String = "ABCABCABC" // Key (censored here) } fileprivate struct Payload: Encodable { let iss: String = "ABCABCABC" // Team-ID (censored here) let iat: Int = Int(Date().timeIntervalSince1970) } extension Data { func urlSafeBase64EncodedString() -> String { return base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") } } Code to send the push notification func SendPushNotification(category: ConversationCategory, conversationID: UUID, title: String, subTitle: String?, body: String, devicesToSendTo: [String]) { // Für alle Felder s. https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification let payload = [ "aps": [ "alert": [ "title": title, "subtitle" : subTitle ?? "", "body": body ], "category" : category.rawValue, "mutable-content": 1 ], "conversationID": conversationID.uuidString ] as [String : Any] // Ggf. Token setzen setNewTokenIfNeeded() guard let currentToken = currentToken else { NSLog("Token not initialized.") return } NSLog(currentToken) // Notification an alle angegebenen Devices schicken let bundleID = "com.TEAMID.APPNAME" for curDeviceID in devicesToSendTo { NSLog("Sending push notification to device with ID \(curDeviceID).") let apnServerURL = "https://api.sandbox.push.apple.com:443/3/device/\(curDeviceID)" var request = URLRequest(url: URL(string: apnServerURL)!) request.httpMethod = "POST" request.allHTTPHeaderFields = [ "authorization": "bearer " + currentToken, "apns-id": UUID().uuidString, "apns-topic": bundleID, "apns-priority": "10", "apns-expiration": "0" ] request.httpBody = try! JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted) URLSession(configuration: .ephemeral).dataTask(with: request) { data, response, error in if let error = error { NSLog(error.localizedDescription) } if let data = data { NSLog(String(data: data, encoding: .utf8)!) } }.resume() } } On a similar note, some people seem to encounter this error when using the prettyPrinted option for the JSON serialization (i.e., in request.httpBody = try! JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted). Could this be the culprit, given our secret key contains „/„ and „+“? Many thanks!
0
0
67
1d
Action Required: Apple Push Notification Service Server Certificate Update
On December 6, 2024, I received the following email. Does this mean that there is something that needs to be done on the app side or on the Firebase side? Currently, in our project, we are using Firebase to set up push notifications. If anyone knows how to deal with this or has taken any action, could you tell me what specific steps you took? Action Required: Apple Push Notification Service Server Certificate Update As we announced in October, the Certification Authority (CA) for Apple Push Notification service (APNs) is changing. APNs will update the server certificates in sandbox on January 20, 2025, and in production on February 24, 2025. To continue using APNs without interruption, you’ll need to update your application’s Trust Store to include the new server certificate: SHA-2 Root : USERTrust RSA Certification Authority certificate. To ensure a smooth transition and avoid push notification delivery failures, please make sure that both old and new server certificates are included in the Trust Store before the cut-off date for each of your application servers that connect to sandbox and production. At this time, you don’t need to update the APNs SSL provider certificates issued to you by Apple.
1
1
303
4d
Inquiry About Silent Push Notification Behavior and Limits
Dear Apple Support Team, I hope this message finds you well. I am reaching out to seek clarification regarding the behavior and limitations of silent push notifications on iOS devices. Specifically, I would like to understand the following: Frequency: Is there a defined frequency limit for how often silent push notifications can be triggered? If so, what is the recommended or maximum frequency for sending silent push notifications to avoid potential issues? Notification Limit: Is there a specific limit on the number of silent push notifications that can be sent to a device within a given time frame? If there are any constraints or best practices, could you please provide guidance? Understanding these details will help ensure optimal implementation and avoid potential disruptions for users. I appreciate your time and assistance. Looking forward to your response. Best regards, Akhil
1
0
74
5d
Subscription permission denied on webapp push
HI, please can someone help? I have a web app where push notifications are in place for Chrome, Firefox, and Edge. Providing the user allows notifications then when they log in for the first time their details are registered to the subscriptions table in the backend. All good so far. When trying to do the same with Safari on Mac I'm faced with this issue: "Safari doesn’t support invisible push notifications. Present push notifications to the user immediately after your service worker receives them. If you don’t, Safari revokes the push notification permission for your site." and the user is not registered in the subscription table with the Safari console just saying variations of this: [Warning] Notification permission denied. (notifications_frontend.js, line 177, x2) [Log] Enable Notifications button clicked (notifications_frontend.js, line 245) [Log] Safari Push Notifications detected (notifications_frontend.js, line 248) [Warning] Safari Push Permission denied. (notifications_frontend.js, line 278) I've found this on an another forrum: "Safari requires that you immediately post a notification when a push message is received. "Immediately" means that it cannot be after some async operation. If you display a notification immediately from the service worker itself, it will stop displaying that error. I cannot remember 100% but I think if you clear your cache and cookies you will be able to receive push messages again if you accidentally get blocked while testing." and I've tried adding buttons to trigger allowing notifications but it all seem to late to get the subscription registered in the subscription table. I'm pretty new to coding so if any has a similar experience and can advice how to get the subscriptions registered when the user logs on for the first time in Safari in a Mac it would be greatly appreciated. Thanks...
0
0
127
1w
CXProvider.reportNewIncomingVoIPPushPayload resulting in NSXPCConnectionInterrupted
We have just been granted access to the com.apple.developer.usernotifications.filtering entitlement, and are following the documented steps for handled E2EE VOIP notifications listed here: https://developer.apple.com/documentation/callkit/sending-end-to-end-encrypted-voip-calls 1 - A user initiates a VoIP call on their app. Their app then sends an encrypted VoIP call request to your server. We do exactly this, Alice calls Bob from her app, sending a notification to our servers. 2 - Your server sends the encrypted data to the receiver’s device using a regular remote notification. Be sure to set the apns-push-type header field to alert. We do exactly this, our server send on a notification to APNS with the apns-push-type header set to alert, destined for Bob. 3 - On the receiver’s device, the notification service extension processes the incoming notification and decrypts it. If it’s an incoming VoIP call, the extension calls reportNewIncomingVoIPPushPayload(_:completion:) to initiate the call. It then silences the push notification (see com.apple.developer.usernotifications.filtering). I try to do exactly this. The notification is received by the NSE on Bob's device, which decrypts it and then notices it is a VOIP call from Alice. It prepares a dictionaryPayload with the decrypted data and then calls reportNewIncomingVoIPPushPayload(_:) async throws. This throws an NSXPCConnectionInterrupted error, which when logged shows as below: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.callkit.notificationserviceextension.voip" UserInfo={NSDebugDescription=connection to service named com.apple.callkit.notificationserviceextension.voip} The only difference I can see to the documentation is that I am working in an asynchronous context so am using the asynchronous version of the method, but I don't imagine this should cause an issue? I then supress the notification as documented and this works correctly. Does anyone have any ideas why I am getting this error when calling reportNewIncomingVoIPPushPayload(_:) async throws?
1
0
153
1w
Apple Push Notification service server certificate update
You are probably aware of the upcoming root certificate change for any servers you might have that you use to send push notifications by connection to APNs. If you are not, here is the announcement. We have been getting some questions about this, and understand not everyone is familiar with their server setup. First, we would like to clarify that this is only a change to your server's certificate trust store. You do not need to update anything else, like your APNs push certificates, the build certificates and provisioning profiles for your team/app, and so on. All you need to do is to install the mentioned new root certificate to your push server's trust store. If you are using a 3rd party push provider, it is them who will need to handle their servers. But you may want to double check with them nevertheless. If you are managing your own push servers that connect to APNs directly, then it is your responsibility to download and install the root certificate mentioned in the above link on your server(s). Unfortunately we cannot provide specific instructions on how to install this root certificate on every kind of server out there. Each server operating system/push server software will have different ways these root certificates are installed, which is out of scope of our support abilities. If you are not sure how to do this, I would recommend you seek help for this from your server-side developers or server admins. Or, if you don't have access to such resources, you can ask the support channels for your system the question: How do I install a root certificate? We have setup a test server at 17.188.143.34:443 that you can use to try and send pushes to test whether your new root certificate is correctly installed. An alternative way to test this would be, from a terminal prompt: openssl s_client -connect 17.188.143.34:443 -servername api.sandbox.push.apple.com -verifyCAfile USERTrustRSACertificationAuthority.crt -showcerts Change the parameter to the -verifyCAfile argument to point to your trust store, and it should allow you to validate Sample return results would be: Connecting to 17.188.143.34 CONNECTED(00000003) depth=2 C=US, ST=New Jersey, L=Jersey City, O=The USERTRUST Network, CN=USERTrust RSA Certification Authority verify return:1 depth=1 CN=Apple Public Server RSA CA 11 - G1, O=Apple Inc., ST=California, C=US verify return:1 depth=0 C=US, ST=California, O=Apple Inc., CN=api.sandbox.push.apple.com verify return:1 Argun Tekant /  DTS Engineer / Core Technologies
0
0
200
1w
Persist and deliver scheduled local notifications after app update
I have an app available for download in the Apple App Store. The app sends local notifications, which are scheduled at the user's request once the app launches. I've recently learned that when new versions of my app are deployed and automatically update on the user's device, previously scheduled local notifications are deleted. Given my app design, the user can re-launch the app in order to re-schedule the local notifications. This is a bit of a problem, though, because part of my app's value is in reminding the user - so after requesting a local notification, the user expects to receive a local notification and then launch the app, not the other way around. Given this, I've been exploring solutions so my app continues to function as expected (including delivering local notifications, even if the app hasn't yet been launched) after an app update. I've explored .backgroundTasks(), but they too are apparently deleted with an app update and require the app to be re-launched first to work as expected. Another solution might be to use push notifications instead of local notifications, but that seems like a very involved solution if I'm just looking to make sure that local notifications persist after an app update. I can't be the only person to have this dilemma - am I overlooking a simple solution?
2
0
133
1w
Can't get forum notifications to work in Safari
Every time I visit these forums, a banner is displayed at the top asking me to opt-in to notifications. I click "opt-in," the banner disappears, and no notifications are sent. If I visit my forum profile, it says my browser isn't allowing notifications: If I look in Settings-&gt;Websites, in the list of "These websites have asked for permission to show alerts in Notification Center," there are no apple.com websites whatsoever, including developer.apple.com. "Allow websites to ask for permission to send notifications" is checked, and I have many other websites in that list. I consider this to be a bug in Safari, but maybe it’s an issue with the forum itself (although I doubt it). I've submitted a Radar for it, but haven't heard anything back (I never do). EDIT: I realize I should've put this in another category, but it won't let me change that now.
1
1
244
1w
Does Firebase Push Notification Service Need New Certificates Due to APNs Update
Hi, With the upcoming changes to the Apple Push Notification service (APNs) server certificates — including the SHA-2 Root: USERTrust RSA Certification Authority certificate update — I wanted to clarify if we need to take any action with Firebase Cloud Messaging (FCM). Since we’re using FCM to send push notifications to iOS devices, does Firebase also need to update its server certificates in response to these changes, or will Firebase handle the updates automatically? We understand that Apple recommends updating our Trust Store to include the new certificates for APNs, but we’re unsure if any action is needed on our end for FCM specifically. Thanks in advance for the clarification!
4
2
4.3k
Dec ’24
Xcode16.1&iOS18.1.1 Debugging App, unable to respond “didRegisterForRemoteNotificationsWithDeviceToken” delegation
I am an iOS development engineer. Recently, I updated the Xcode version to 16.1 (16B40) and updated my debugging device (iPhone 15) to iOS 18.1.1. However, I found that I could not respond to the delegate method. I confirmed that my code, certificate, Xcode settings, and network environment had not changed. Simply executing application.registerForRemoteNotifications() in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool did not receive a response(didRegisterForRemoteNotificationsWithDeviceToken or didFailToRegisterForRemoteNotificationsWithError ). In the same environment, when I switched to another device for debugging (iOS 17.0.3), the delegate method would respond. I really don't know what to do, I hope someone can help me, I would be very grateful. Please note: Everything is normal when using devices before iOS 18.1.1 version
2
0
298
Dec ’24
Notifications on iOS sourced from a machine on an offline local network
We have a device which is an appliance and we are developing a control interface app for macOS and iOS/iPadOS. How can we set up our iOS application to grab information from a local network device while it is in the background in order to show notifications? Communication between the Apple device and our device is via local networking and the device is designed to be used on networks without internet connections. On networks with internet connections we could forward events from the device, via a server and APNS push notifications, but that isn't valid here. Events occur on our device and are forwarded to clients, who are subscribed to Server-Sent Events. On macOS this works well and the application can receive updates and show Notification Center notifications fine. On iOS we are using a BGAppRefreshTaskRequest with time interval set to 1 minute, but it appears that we get scheduled only every few hours. This isn't very useful as notifications just arrive in batches rather than in a timely manner. All normal networking is closed when the app goes into the background, so we cannot keep the SSE request open. Another idea which we haven't tried yet: Creating a new endpoint on the device which keeps the connection open until a notification arrives, then using background URLSession to poll on that endpoint. Would that work? It seems like a mis-use of the API perhaps?
9
0
380
Dec ’24
Notification Received in Kill Mode but No Method Invoked in iOS
Hello Apple Developer Team, I am facing an issue with remote notifications in my iOS app. When the app is in a terminated (kill) state, notifications are successfully received by the device, but none of the app's handlers (like _firebaseMessagingBackgroundHandler in Flutter) are invoked. This is impacting our ability to process silent notifications or perform background tasks reliably when the app is not running. Steps to reproduce: Send a remote notification with content-available: 1 in the payload. Confirm the notification is received by the device while the app is in kill mode. Observe that no background or foreground notification methods are triggered in the app. Expected Behavior: The app should invoke the background handler to process the notification payload, even in a terminated state. Observed Behavior: The notification is delivered to the device, but no app-level processing occurs because none of the methods are triggered. Can you please confirm if this is the intended behavior due to iOS limitations, or if there is a configuration or alternative solution to allow background handlers to execute in such scenarios? Any guidance or clarification would be highly appreciated. Thank you!
1
0
247
Nov ’24
Critical alert delay
I am sending push notifications to the app with critical alerts, but there is a significant delay. If the number of target devices is 1000 or less, notifications will be received normally within a few seconds to a minute. Once the number of target devices exceeds 1000, some devices will arrive quickly (normally within a few seconds to 1 minute) and others will arrive late (3 minutes to 15 minutes, divided into hundreds of items). In severe cases, notifications to more than 80% of devices will be delayed. Example: If you send 3000 notifications at once,  1 minute: Notify 400 items  5 minutes: Notify 1000 items  10 minutes: Notify 1000 items  13 minutes: Notify 600 items *The timing of 5 minutes, 10 minutes, and 13 minutes changes every time and is not at regular intervals. We understand that according to the push notification specifications, sending several thousand messages at once is not a problem. Please let me know if there is a rule, such as sending 1000 items at a time, in order to deliver quickly and with minimal delay.
3
0
332
Nov ’24
Difference between Push delivery metrics in APNs console vs. 410 code for unregistered tokens
Hi there, We’re using APNs Push delivery metrics, which provide a breakdown including metrics like Received by APNs, Delivered to Device, and Discarded - Token Unregistered. To track unregistered tokens on our end, we also monitor the 410 error responses from APNs, which typically indicate that a token is no longer valid. However, we’ve noticed a discrepancy: the number of 410 errors we receive is much lower than the Discarded - Token Unregistered count shown in the APNs console. Is this difference expected? Specifically, does APNs sometimes know that a token is unregistered but still return a success status to us when we attempt to send a push to that token? Thank you for any insights you can provide!
1
0
342
Nov ’24
notificationclick event not triggered if the progressive web app(pwa) is not opened
Hello, notificationclick event cannnot be triggered if the progressive web app(pwa) is already opened. I have tried many methods including client.focus() clients.openWindow() client.postMessage() message event listening Delayed message queue (to let the client being opened) preventDefault() in notificationclick event Activation event.waitUntil() The situation is that when the device install the pwa twice, the second pwa works normally. However, it is nonsense to ask users install the pwa twice. Is it a bug in Webkit and will it be fixed in the future? is there a workable example? Background: using web-push, iOS 17/18 Thanks a lot
0
1
301
Nov ’24
Help Needed: Repeated Local Notifications for Alarm App When App is Closed
I am currently developing an alarm app, and I’ve noticed that apps like Super Alarm and Alarmy are able to send local push notifications every 3 seconds after a specified time, even when the app is completely closed and in Airplane Mode. The notifications continue until the user opens the app. I’m trying to implement this functionality, but I haven’t been able to figure out how. Could anyone provide guidance on how to achieve this?
1
0
299
Nov ’24
APN's not delivering to macOS devices
Hello, I am building a swift macOS app and have noticed issues today with delivering APN's to both development and production devices. Similar to this thread the only way I can get them to deliver temporarily is to do one of: Change the bundle ID of my app to a new bundle ID, then start it up. I will usually get the first notification. Reset my network (either wired ethernet or wifi, typically both) Using the push notifications console for development sends, I see the message "discarded as device was offline" in the delivery log even though the device is still online and was just registered when I got back the deviceToken. If I set an expiration on development notifications then the delivery log says "stored for device power considerations" and the notification will then send once I do one of the above steps (new bundle or reset network). Previous to today the notifications were sending immediately and I had no issues getting them. Is there something I can do to fix this problem, is it a problem with the APN provider, or is it something else I haven't thought of? A unique ID for an expiration-based notification is 1755def8-1a44-cbcf-c64b-64e435c30f81, and a non-expiry is d7a72b46-0c64-4500-0abc-3734f9efbd90.
3
0
325
Nov ’24
safari push notification endpoint always empty
Hi, I implemented push notifications on my PWA, and it work fine with all browsers except with Safari. I followed all the recommendations given by Brady Eidson in this video : Meet Web Push for Safari And the result is that all the push notification process work fine with others browsers, from the subscription to the notification delivery and display. But with Safari the endpoint is always empty and I do not understand why. No error is triggered during subscription. Just the result is a subscription with an empty endpoint. I have the same result on iPad, iPhone and iMac. Everything is working well with others browsers or with android smartphone. But contrary to what Brady Eidson promised in his video, it does not work with Safari.
3
0
346
Nov ’24