Send push notifications to Mac, iOS, iPadOS, tvOS devices through your app using the Apple Push Notifications service (APNs).

Posts under APNS tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

How to get pushTokenUpdates when starting a Live Activity via Push Notification
I'm trying to build a Live Activity extension. I can successfully start my live activity via push notification. The problem is, when I start live activity from my app, I can get pushTokenUpdates since I control everything and run the for loop that gets pushTokenUpdates. But the code that gets pushTokenUpdates isn't called when I start live activity with push notification since system starts it automatically (maybe it is called, but I don't know when and where). Where am I supposed to get pushTokenUpdates when I start Live Activity using push notification to send them to my server? The relevant code is below: for await data in activity.pushTokenUpdates { let token = data.map { String(format: "%02x", $0) }.joined() Logger().log("Activity token: \(token)") // send token to the server }
3
3
348
Aug ’24
Issues with Silent Notifications in Parental Control App Using FCM and Background Tasks
Hello, We are developing a parental control app consisting of two parts: a parent app to manage settings and a child app to enforce these settings using iOS's Screen Time API, CoreData, and other components. We've attempted to use silent notifications with Firebase Cloud Messaging (FCM) to communicate updates from the parent app to the child app. Our current implementation involves background modes for remote messages and background tasks. However, we're facing a challenge: while normal FCM push notifications with a 'message' key work as expected, silent notifications (with only a 'data' key) do not trigger the desired behavior in the child app, even though FCM returns a success response. We're looking for assistance with two main issues: Alternative Approaches: Is there a better way to notify the child app of changes? We're considering a system where the child app periodically checks for updates via API and then updates CoreData and managed settings. Any recommendations for this architecture or a more reliable notification system would be greatly appreciated. Debugging Silent Notifications: If our current approach using silent notifications is feasible, could someone help us debug why these notifications are not working as expected? We've been stuck on this for a week, and any help would be a lifesaver. Here's the relevant part of our AppDelegate code: import UIKit import FirebaseCore import FirebaseMessaging import BackgroundTasks @objc class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { let gcmMessageIDKey = "gcm.message_id" let backgroundTaskIdentifier = "com.your-company.your-app.silentnotification" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self // Register for remote notifications UNUserNotificationCenter.current().delegate = self application.registerForRemoteNotifications() // Register background task BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: nil) { task in self.handleBackgroundTask(task: task as! BGProcessingTask) } return true } // Handle incoming remote notifications func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if let aps = userInfo["aps"] as? [String: Any], let contentAvailable = aps["content-available"] as? Int, contentAvailable == 1 { // This is a silent notification handleSilentNotification(userInfo: userInfo, completionHandler: completionHandler) } else { // This is a regular notification Messaging.messaging().appDidReceiveMessage(userInfo) completionHandler(.newData) } } // Handle silent notification func handleSilentNotification(userInfo: [AnyHashable: Any], completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let request = BGProcessingTaskRequest(identifier: backgroundTaskIdentifier) request.requiresNetworkConnectivity = true do { try BGTaskScheduler.shared.submit(request) performAPICall { result in switch result { case .success(_): completionHandler(.newData) case .failure(_): completionHandler(.failed) } } } catch { completionHandler(.failed) } } // Handle background task func handleBackgroundTask(task: BGProcessingTask) { task.expirationHandler = { task.setTaskCompleted(success: false) } performAPICall { result in task.setTaskCompleted(success: result != nil) } } // Perform API call (placeholder implementation) func performAPICall(completion: @escaping (Data?) -> Void) { // Your API call implementation here // For testing, you can use a simple delay: DispatchQueue.main.asyncAfter(deadline: .now() + 2) { completion(Data()) } } } extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("FCM token: \(fcmToken ?? "nil")") // TODO: Send this token to your server } } Additionally, here is how we're sending notifications from the server side using Node.js: // Import the required Firebase Admin SDK (assumed to be initialized elsewhere) // const { getMessaging } = require('firebase-admin/messaging'); /** * Sends a background push notification to an iOS device * @returns {Promise<string>} The message ID if successful * @throws Will throw an error if the sending process fails */ async function sendBackgroundPushNotification() { // Construct the message object for a background push notification const message = { apns: { headers: { // Set the priority of the push notification "apns-priority": "5", priority: "5", // Indicate that this is a background refresh notification "content-available": "1", content_available: "1", // Specify the push type as background "apns-push-type": "background", // Set the topic to your app's bundle identifier "apns-topic": "com.your-company.your-app", // Replace with your actual bundle identifier }, payload: { aps: { // This tells iOS to wake up your app in the background "content-available": 1, }, }, }, // Custom data payload to be sent with the notification // Modify this object to include the data you want to send data: { // Add your custom key-value pairs here }, // Uncomment the following block if you want to include a visible notification // notification: { // title: "Notification Title", // body: "Notification Body", // }, token token: "DEVICE_FCM_TOKEN_PLACEHOLDER", }; try { // Attempt to send the message using Firebase Cloud Messaging const response = await getMessaging().send(message); console.log("Successfully sent background data to iOS:", response); return response; } catch (error) { console.error("Error sending background data to iOS:", error); throw error; } } // Example usage: // sendBackgroundPushNotification() // .then((response) => console.log("Message sent successfully:", response)) // .catch((error) => console.error("Failed to send message:", error)); We would really appreciate any insights or guidance on these issues. Thank you!
5
0
684
Aug ’24
Push Notification Error - 400 Invalid Push Token
We are using fcm to send push notifications. Recently we noticed some of our ios devices were not receiving push notifications, failing. By using the Push notification console we can see we are failing from APNS, with a 400 - Invalid Push Notification. Once this occurs we dont get push notifications on that device. We have tried re-logging in and re-installing the app. This does not work initially. However eventually they start working again after re-installing, usually after at least a day. { "code": 400, "message": "bad-request", "reason": "Invalid push token", "requestUuid": "ee04b0f1-c6aa-4b5e-87c0-7df754801d6f" } Any ideas why the token is deemed invalid? Is there any way to get more details?
3
0
800
Aug ’24
APNS push is not received by device when sent via backend despite 200 OK response received
I am attempting to send a push notification via APNS from a supabase edge function (deno/typescript). I receive a 200 OK response from APNS, and using the "apns-unique-id" I am able to look up the notification in the dashboard which shows the notification was successfully sent to the device. However the app/device does not receive the push. Using the dashboard, I can successfully send a test push to the device, and I also have FCM already implemented and working, so I assume the iOS/client-side setup is not the problem. I also verified that my generated JWT and device token are valid via the dashboard, plus I'm getting 200 back with the request, so I also assume that auth is not an issue either. Yet even with a simple alert payload such as below, nothing comes through. What else could be causing this issue? Perhaps I'm missing a step? The details of the request I'm making are below: url = "https://api.sandbox.push.apple.com:443/3/device/{deviceToken}" headers = { "authorization": "Bearer {jwt}", "apns-push-type": "alert", "apns-topic": bundleId, "apns-priority": 10 } body = { "aps": { "alert": { "title": "Test Notification", "body": "This is a test notification.", "sound": "default" } } }
1
0
503
Jul ’24
web app push notifications on native WKWebView
Hi, I'm required to create an app with a WkWebView, this web view should point to a webApp wich should send web notifications. this web app, downloaded on the "home" of my device, is working. But from what I can see on the web, it is not possible for me having a native swift app, with a WkWebView , receiving notifications from the web app. is it right? or there is a way to achieve this? I understand that WkWebView view are not working with Service Workers which it seems to me they are required. could someone help me? thanks in advance
3
0
373
Jul ’24
start live activity via push notification pushToStartTokenUpdates
I have success with starting live activity from the server but I have some questions and problem first I get pushToStartTokenUpdates only once what if my user missed it? so I could not start from the server pushToStartTokenUpdates how long I can use? will it refresh the new token? for start live activity via push notification? does token I get from pushToStartTokenUpdates use for only start live activity event from server and can't use for update ? so if token get from pushToStartTokenUpdates for only start live activity via remote so how can I obtain the token for update ?
0
0
386
Jul ’24
Error while donwloading APN Key
We have created a new Key for APN services but when we click the download button we get to following error: è stato fornito un valore non valido 'undefined' per il parametro 'keyId' (An invalid value 'undefined' was provided for the 'keyId' parameter) Already tried we a new one but got the same error. Thanks
1
0
350
Jul ’24
The app must be updated to use the new Push to Talk framework pop up display even after adding PTT framework
Hello All, I am getting following popup for our application, I have implemented PTT Push To Talk framework by following https://developer.apple.com/documentation/pushtotalk/creating-a-push-to-talk-app We are using following VoIP entitlements, Our app support from iOS 12 i) com.apple.developer.pushkit.unrestricted-voip ii) com.apple.developer.pushkit.unrestricted-voip.ptt We have updated app with new Push To Talk framework and it's working fine. Our app's minimum deployment target is iOS-12.0 , So app will also work without using PTT framework for older iOS. Question, Why popup display even after new Push To Talk framework implementation? what should I do to remove this popup from showing? Should I do any other setting to complete this framework? Thanks.
5
0
674
Jul ’24
I have a few questions about Location Push Service and Screentime Family controls.
Hello. I have a few questions about Location Push Service and Screentime Family controls. Do Location Push Service and Screentime Family controls require permission to be tested with development builds? Will my application for permission to test be approved? How long does it take to receive results if I apply for permission? Is it possible to use the functionality of the Screentime api in LocationPushServiceExtention? Is it possible to control remotely even if I apply for Screen time API's Family Controls permission as an individual? (ex. Change Screen time settings by push from server) Information is needed to plan an app that includes both functions. Thank you
2
0
407
Jul ’24
Receiving 403 (InvalidProviderToken) from APNs Send Notification service
Experiencing 403s (InvalidProviderToken) [https://api.push.apple.com/3/device/] due to invalid or unverifiable provider tokens. We have noticed that after retrying the request inline, the notification is delivered successfully without any changes to the request even with same authorization token. Someone please guide or suggest why it is happening as the JWT token which is generated is correct because we are caching the jwt token and using the same token to send out the subsequent request which is kind of successfull. Sending the notification for multiple team Ids under the same application.
1
0
601
Jul ’24
Not getting notifications from some apps on iOS 17.5.1
Tried all these steps Force restart DIsabled focus mode Notifications are enabled in both device and in app settings Disabled summary notifications. Tried sending notification from pusher tool, that also is not showing up in the center, for the device effected but on another device it is working fine for the same application(same version too) What could be the reason and a possible solution?
2
0
459
Jul ’24
Are device tokens which is registered with APNs unregistered after App transfer?
Good day! Recently, we are doing the feasibility study for transferring our App from team A to team B. Our App uses Apple Push Notifications service (APNs) and we know we need to recreate certificates after the App transferring. We have a question that can we use the old device tokens which are registered before the transferring to send the notification to users? For example, Before the transfer: User A installs App and upload tokenA_old to our service server. Our service server stored it into our database. After the transfer: User A doesn’t launch App and we only have the tokenA_old which is stored in our server. After we recreate push notification certificate, can we send notification with tokenA_old to user A? Or his device token will be renewed after the App is transferred? Does he need to launch App and get the new registered device token from APNs and upload it to our server again? override func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined() uploadDeviceToken(deviceTokenString) } We want to check above question for following tokens: deviceToken (Push notification) API: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622958-application pushToStartToken (Live activity) API: https://developer.apple.com/documentation/activitykit/activity/pushtostarttoken Does deviceToken will be renewed after the App is transferred? Does pushToStartToken will be renewed after the App is transferred? Thank you.
1
0
369
Jul ’24
Can I use Screentime API in CLLocationPushServiceExtension?
Can I use Screentime API in CLLocationPushServiceExtension? For example, I am curious about whether it is possible to set a managed setting in the Screentime API to limit app usage time or change the time limit. If the implementation of the above function is impossible or causes rejection by the App Store, is there a way to use the Screentime API in the background through push notification?
1
0
473
Jul ’24
Connection Reset between F5 and APNS
Our Java backend application is responsible for sending millions of push notifications. However, we are encountering an issue where thousands of connection resets occur daily. This irony leads to an inability to keep up with the volume, resulting in a lag that affects real-time performance. The application is built on Java, utilizing JDK 1.8 and the Apache HttpClient for network communications. Below is the Maven dependency we use: XML Additionally, we employ Spring’s RestTemplate to dispatch push notifications. Here is a snippet of the pseudo-code used to call the Apple Push Notification service (APNs): Java ResponseEntity postForEntity = restTemplate.postForEntity(apnsURL, entity, responseType); getResponse(aPNSResponse, postForEntity); AI-generated code. Review and use carefully. More info on FAQ. It’s important to note that our calls to APNs are not made directly but are routed through an F5 load balancer, which then communicates with the APNs endpoint. Could someone guide us in the right direction to resolve these connection reset issues?
4
0
355
Jul ’24