I am developing a new App that uses Push Notifications. I completed the development of the App itself and I can send Push Notifications from the CloudKit and receive it on my phone.
My problem is sending the Push Notifications from our service API to Apple. If I use the production address gateway.push.apple.com, I can send messages, but they don't work for my new App because it is in development and not yet released. If I use the sandbox address api.sandbox.push.apple.com, I get the following exception:
System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it. [::ffff:17.188.143.98]:2195
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)
--- End of stack trace from previous location ---
at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)
at System.Net.Sockets.Socket.Connect(String host, Int32 port)
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at System.Net.Sockets.TcpClient..ctor(String hostname, Int32 port)
The service API for sending Push Notifications was developed in C# .NET 8.0.
Constants:
private readonly string _hostname = "api.sandbox.push.apple.com";
private readonly int _port = 2195;
The code for sending a message.
public async Task Send(string? subtitle, string? title, string message, string deviceId)
{
var payload =
"{ \"aps\": { " +
"\"alert\": { " +
"\"title\": \"" + title + "\", " +
"\"subtitle\": \"" + subtitle + "\", " +
"\"body\": \"" + message + "\"" +
"} " +
"} " +
"}";
try
{
Debug.WriteLine($"apple api request: {payload}");
using var client = new TcpClient(_hostname, _port);
var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate));
var certificatesCollection = new X509Certificate2Collection(_certificate);
await sslStream.AuthenticateAsClientAsync(_hostname, certificatesCollection, SslProtocols.Tls12 | SslProtocols.Tls13, true);
var array = DataToBytes(deviceId, payload);
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch(Exception exception)
{
Debug.WriteLine(exception);
}
}
The certificate that is used in this code was read beforehand:
var clientCertificate = new X509Certificate2(iOSApp.Certificate, iOSApp.CertificatePassword);
We are using a p12 certificate file with a private password.
Again, it works great for an App in Production but not at all for an App in Development. I made use that I use a new p12 developer certificate for the new App when I tested. I also tested with a p12 production certificate. I get the same error.
Any help is appreciated.
Notifications
RSS for tagLearn about the technical aspects of notification delivery on device, including notification types, priorities, and notification center management.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello, I'm from Microsoft team maintaining push notification api behind Teams platform.
We are experiencing strange and short error spikes towards APNS that seem to mostly correlate worldwide. We checked the networking and push request code but could not find what could be causing this. These error spikes are all timeouts or connection resets (by remote host, ie. APNS servers) and seem to come and go randomly:
Would it be possible to check this for outages or some other metrics on your side or investigate why would it happen? Since it's worldwide it seems unlikely it's something broken on our side. We are using the standard APNS http2 endpoint with modern support for all RFC features (so everything should work normally).
Mind you, our api might be in a unique position because of the volume of notifications (in the billions per day).
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.
Hello,
I have a couple of questions regarding the change of the Certification Authority (CA) for Apple Push Notification service (APNs) and I will be grateful for any answers.
Does it require only making sure the server machine has the SHA-2 Root: USERTrust RSA Certification Authority certificate included in Trust Store (/etc/ssl/certs/USERTrust_RSA_Certification_Authority.pem with SHA256: 8a3dbcb92ab1c6277647fe2ab8536b5c982abbfdb1f1df5728e01b906aba953a) ?
Should the Certificate Signing Request be updated (that one that is uploaded to https://identity.apple.com/pushcert/) ?
Does it have any connection with the certificates that are created on https://identity.apple.com/pushcert/ ?
Is the push type "mdm" affected too?
Which certificate should be added and where specifically? Is it for Certificate Signing Request to https://identity.apple.com/pushcert/ or the certificate that is generated on https://developer.apple.com/account/resources/certificates/list or like mentioned in the first question?
Can a certificate for sandbox environment be created on https://identity.apple.com/pushcert/ ?
Thank you for any help.
I am trying to issue the "start" APNs push notification to start a live activity for my iOS app. The notification appears to send correctly, there is no error message, but the live activity never appears for any of my users (users are in TestFlight).
In addition to issuing the APNs commands from my server, I have also tried using the CloudKit Push Notification Console to manually generate a "start" notification. It submits correctly but the live activity never starts.
I have also checked the Console app to watch the device logs and see if iOS is rejecting/throttling the live activity but I don't see any activity related to the start message at all.
Here are some details:
App bundle ID: `com.penzu.moodmoji`
APNs topic: `com.penzu.moodmoji.push-type.liveactivity`
APNs push type: `liveactivity`
Recent apns-id: `7b633309-b7fd-4163-b620-776efa04f315`
APNs payload:
{
"aps": {
"timestamp": 1742651625,
"event": "start",
"content-state": {
"totalDays": 7,
"currentDay": 2,
"progress": 0.29,
"status": "ACTIVE",
"reportReady": false
},
"attributes-type": "GoalActivityAttributes",
"attributes": {
"totalDays": 7,
"currentDay": 2,
"progress": 0.29,
"status": "ACTIVE",
"reportReady": false
},
"alert": {
"title": "It's day 2!",
"body": "Don't forget to record every time you feel anxious today."
}
}
}
I can confirm that LiveActivities started by the iOS app with ActivityKit work correctly, and the app does appear to be receiving pushToStartTokenUpdates:
struct GoalActivityAttributes: ActivityAttributes, Sendable {
struct ContentState: Codable & Hashable, Sendable {
let totalDays: Int
let currentDay: Int
let progress: Double
let status: String
let reportReady: Bool
}
let goal: SimpleGoal
}
for await nextStartToken in Activity<GoalActivityAttributes>.pushToStartTokenUpdates {
// send nextStartToken to server...
}
The app I'm testing with is in TestFlight, using the production APNs environment.
I am trying to retrieve delivered notifications using UNUserNotificationCenter.getDeliveredNotifications(completionHandler:), but I have encountered an issue:
Notifications triggered by UNTimeIntervalNotificationTrigger or UNCalendarNotificationTrigger appear in the delivered list.
However, notifications triggered by UNLocationNotificationTrigger do not appear in the list.
Here is the code I use to fetch delivered notifications:
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
for notification in notifications {
print("Received notification: \(notification.request.identifier)")
}
}
The notification is scheduled as follows:
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Test Notification"
content.body = "This is a location-based notification."
content.sound = .default
let coordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) // Example coordinates
let region = CLCircularRegion(center: coordinate, radius: 100, identifier: "TestRegion")
region.notifyOnEntry = true
region.notifyOnExit = false
let trigger = UNLocationNotificationTrigger(region: region, repeats: false)
let request = UNNotificationRequest(identifier: "LocationTest", content: content, trigger: trigger)
center.add(request) { error in
if let error = error {
print("Error adding notification: \(error.localizedDescription)")
}
}
Why does getDeliveredNotifications not return notifications that were triggered using UNLocationNotificationTrigger?
How can I retrieve such notifications after they have been delivered?
I’m using Appnotic from my server to send notifications for an emergency service, where it is critical that notifications are delivered immediately.
My payload looks like this:
"aps": {
"alert": "Test alert",
"sound": {
"critical": 1,
"name": "sound.wav",
"volume": 0.5
},
"content-available": 1,
"category": "alert"
},
"topic": "com.fireservicerota.FSR-Primary-Alerting",
"custom_payload": {
"id": "11",
"type": "alert",
"incident_id": 23434,
"incident_response_id": 2652343,
"expiration_time": "2024-06-06T16:59:05+01:00"
}
}
I already have the critical alert entitlement and background processing enabled. Everything seems fine when debugging, but I’m experiencing issues:
• Some notifications never arrive
• Around 60% of notifications arrive with noticeable delay
Since this is an emergency app, delivery speed is crucial. What could be causing this inconsistency?
When I use https://api.push.apple.com/3/device/e0ae826f3905b010e37c4a07e873481b8446c9dc2788511b2995992884468068
Return error message: {"reason":"BadDeviceToken"}
When I use https://api.development.push.apple.com/3/device/e0ae826f3905b010e37c4a07e873481b8446c9dc2788511b2995992884468068
Return error message:{"reason":"TopicDisallowed"}
why?
when I implementation the UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
var status = ""
if (UIApplication.shared.applicationState == .active) {
status = "active"
} else if (UIApplication.shared.applicationState == .background) {
status = "background"
} else if (UIApplication.shared.applicationState == .inactive) {
status = "inactive"
}
completionHandler()
}
I find that UIApplication.shared.applicationState == .background this case can not execute when application is in background。
why applicationState is inactive not background?
I have tried setting a 'apns-expiration' to current time + 30 seconds and also a value '0'. But still my voip app receives the voip push notification after 2-3 minutes. Till this time, caller has already hung up the call. But the receivers phone still rings on receiving the push notification as we have to report it to CallKit.
Am I missing something or there is no way and even 'apns-expiration' does not guarantee timely delivery of Voip push notifications or discard if it is expired.
I have set 'apns-priority' to 10 already as recommended.
Hi) we have two ios apps in same Firebase project - with different apple bundle ids. One of them had connected APNS with Firebase and everything had worked perfectly - push notifications where delivered every time. But recently we occationaly put same APNS to other our Firebase's ios app and as result we lost all pushes - on both app. After deletion APNS from both of them and reconnecting APNS to app with proper apple bundle id push notifications didn't start to work.
could you please suggest what we are suppose to do to resolve issue?
I want to update my lockscreen LiveActivity via Broadcast Push Notification, but updating always fails - but ending always works.
Payload with "update" is completely ignored:
{"aps":{"timestamp":1685952000,"event":"update","content-state":{"currentSlotName":"Debug1","nextSlotName":"Debug2"}}}
Same payload with "end" works, the view is refreshed with the new content-state:
{"aps":{"timestamp":1685952000,"event":"end","content-state":{"currentSlotName":"Debug1","nextSlotName":"Debug2"}}}
Via the MacOS Console I am able to see that both events happen to end up on the device. I am sending these Broadcast Push Notifications via Apple's Push Notifications Console.
To receive silent push notifications in the background, I need to include content-available payload into my APNS push notification, and have application(_:didReceiveRemoteNotification:fetchCompletionHandler:) implemented.
When I send a push notification, my app receives and handles it with the above method.
This works correctly and is straightforward to test when the app is running in foreground or background on my device.
I would like to test if my app is woken up correctly from scratch and does the above work. But how do I do this? How do I get my app into the state where it is started when it receives a silent push notification?
When the user force-kills the app, the notification is not delivered. This is also the case when I as a developer force-kill the app which I am testing. I assume it also applies when I force-stop the app running on my device from within Xcode.
Is there any way for me as a developer to terminate the app, which does not count as “force killing”, and would reliably start the app when it receives the background notification?
I'm encountering an issue with our legacy Objective-C codebase that uses UIApplicationDelegate.
Here are the steps to reproduce the issue:
Uninstall the application from the device.
Install and launch the application.
As part of the launch event, the client requests notification permission.
The permission prompt is still displayed, even though the client receives a remote notification token (which appears to be a cached one).
I followed the same steps with a sample app built with Swift (SwiftUI), and this issue did not occur. In the Swift app, I consistently received a delegate<didRegisterForRemoteNotificationsWithDeviceToken> call after the user allowed the notification permission.
Could you please provide some insights into why this might be happening with only our client?
Topic:
App & System Services
SubTopic:
Notifications
Tags:
APNS
iOS
Notification Center
User Notifications
I'm working on implementing Apple Wallet passes using background push notifications.
My server successfully sends the push notification using APNs. The response from the server is HTTP/2 200, and the device receives the push — I can confirm this from device logs.
However, the device logs show the following error:
"Failed to parse JSON message payload for topic "
"Unable to deserialize JSON message payload"
My payload is below 2 payload.
//string payload = "{"aps":{"content-available":1}}";
string payload = JsonConvert.SerializeObject(new
{
aps = new Dictionary<string, object>
{
{ "content-available", 1 }
}
});
string curlArgs = $"-s -o nul -w \"%{{http_code}}\" " +
$"--data-binary \"{payload}\" " +
$"-H \"apns-topic: {bundleId}\" " +
$"-H \"apns-push-type: background\" " +
$"-H \"apns-priority: 5\" " +
$"-H \"content-type: application/json\" " +
$"-H \"authorization: bearer {jwt}\" " +
$"--http2 https://api.push.apple.com/3/device/{token}";
I’ve confirmed that:
The device has the Wallet pass installed.
The apns-topic header is set to my passTypeIdentifier.
The apns-push-type is background and apns-priority is 5.
Steps to Reproduce:
Install Wallet pass on iOS device.
Send background push to device using the above payload.
Observe the device logs using Console.app or log stream.
See error: unable to deserialize JSON message payload.
Is there a specific payload format expected for Wallet passes? Or any additional fields required in the push payload to avoid this deserialization error?
Hey Together,
I have seen that critical notifications need to be confirmed by apple to be used.
Sadly I couldn't figure out where to ask for that.
Context: I have a sports tournament app for Beach Handball. There are a couple of Courts like up to 20-25. The main use for that in my app would be to notify first aiders/Medics. Right now they are called in via Speakers or by the referees just writing that into a WhatsApp chat. As this takes a long time and the speakers can be deactivated due to rain, power shortage or even the medics sometimes are not in range to exactly hear the speakers calling them.
To Speed up this process I want them to download the App, Register via an E-Mail or a One Time Code. Now if a referee needs immediate Help from the Medics on their court they can send the Critical alert to the Medics without having to write a chat into a WhatsApp group, to get a call through the speakers 10 minutes later which the medics may not even hear.
A couple of weeks ago we had a player falling on her back/neck/head and they couldn't figure out if she broke her neck or not. Luckily the medics were right next to the court and saw that. but what would happen if they were a couple hundred of meters away and did not notice that? I mean the PA system was off due to a power shortage. someone trying to move her? Risking her death?
And while we are at it we could add those notifications if a team is missing to a court for a game that already should've started. Critical because it is urgent. Those notifications are handled with care.
Hello everyone,
Our team is currently developing a PTT (Push-to-Talk) application using the officially recommended PushToTalk framework. During development, we've encountered a point of confusion regarding the application's behavior after being force-quit by the user.
Based on our understanding of the PushToTalk framework documentation (https://developer.apple.com/documentation/pushtotalk/creating-a-push-to-talk-app/) and the PTChannelManager session restoration mechanism, when a user manually kills the app from the background (App Switcher), the current PTT session (the system session managed by PTChannelManager) should terminate. Subsequent pushtotalk type pushes sent via APNS, without an active session, appear to be silently discarded by the system and cannot wake the app for processing (similar to what Kevin Elliott DTS mentioned in https://developer.apple.com/forums/thread/760506 Point D). This seems to prevent reliable PTT message reception in our app after a user force quits.
However, we've observed that some popular PTT applications on the market (e.g., TenTen) appear to successfully receive and play PTT voice messages from friends even after the user has performed a force-quit action. This behavior seems inconsistent with our test results and understanding based on the standard framework, posing a challenge for us in providing similar reliability using standard methods.
This naturally leads us to wonder how this capability is achieved. We've reviewed developer forums and are aware of the historical existence of a PTT-specific com.apple.developer.pushkit.unrestricted-voip entitlement, which allowed PushKit usage for PTT without CallKit binding. While Apple DTS engineers have repeatedly stated this entitlement is being deprecated and urged migration to the PushToTalk framework (e.g., https://developer.apple.com/forums/thread/763289), we are curious if the observed "wake-after-force-quit" capability might be related to some apps potentially still utilizing this outgoing special entitlement. Alternatively, is there perhaps a mechanism within the standard PushToTalk framework that allows wake-up after force quit that we haven't fully grasped?
Therefore, we'd like to ask fellow developers for clarification and discussion:
When using the standard PushToTalk framework, have others confirmed that the app indeed cannot be woken up by pushtotalk pushes after being force-quit by the user? Is this the expected behavior?
Has anyone successfully achieved a TenTen-like experience (reliable PTT reception after force quit) using only the standard PushToTalk framework? If so, could you share key implementation insights or areas to focus on? (e.g., Is it related to specific usage patterns of the restorationDelegate?)
How do you view this potential discrepancy between standard framework capabilities and the behavior exhibited by some apps? What considerations does this bring to development planning and user experience design (especially when users might have expectations set by the "always-on" behavior of other apps)?
Are there any best practices or specific techniques when using PTChannelManager session management and restoration that maximize PTT message reliability (especially after the app is terminated by the system in the background), while still adhering to the framework's design principles (like user awareness of the session via UI)? [For instance, another developer raised challenges related to PTT framework restrictions here: https://developer.apple.com/forums/thread/773981]
We hope this discussion can help clarify our understanding of the framework and gather community best practices for building reliable PTT functionality while adhering to Apple's guidelines.
Thanks for any insights or shared experiences!
I send APNs notifications to my devices with the CloudKit dashboard. I test with two devices;
Device with Silent Push Working Successfully:
iOS version 16.5.1 (c), Model iPhone Xs
Silent Push Failed Device:
iOS version 15.3.1, Model iPhone Xr
Normal alert notifications work successfully on both devices. But I can't see any log in my project even though silent push is sent successfully on one device.
What I've Checked:
content-available is set to 1.
My app is not in kill state, it is in foreground or pending in the background.
When I send simple notifications, I can see logs in my swift project and notifications on physical devices without any problem.
No, my certificate has not expired and if there was a problem with it, I would not be able to see the normal notifications.
My phone is not in power saving mode and the “Background App Refresh” option is turned on in the app's settings.
Both devices in charging state.
App capabilities: Background Modes is enabled with Remote Notifications, Background Fetch, Background Processing.
CloudKit Dashboard After Sending Silent Push:
My AppDelegate Class In Swift Project:
import SwiftUI
import UIKit
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
return true
}
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)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
logInfo("Received Push Notification: \(userInfo)")
if let aps = userInfo["aps"] as? [String: AnyObject], aps["content-available"] as? Int == 1 {
logInfo("This is a silent push notification")
//DO SOME WORK
completionHandler(.newData)
}
completionHandler(.newData)
}
}
Hello,
I'm trying to use critical alerts on the CarPlay, but I'm facing couple of issues:
Sound of critical alerts is not played by the CarPlay's speakers (played by the iPhone's speakers)
Tapping on a critical alert doesn't open the app like other notifications.
Critical alerts of the app are always shown if the CarPlay is connected, even if the app doesn't have the CarPlay entitlement.
didReceive is not called if the user taps on a notification on the CarPlay.
Any help would be greatly appreciated
I keep getting 401 Unauthorized error when fetching Apple's public keys.
In [14]: print(f"Error fetching public keys: {response.status_code} {response.text}")
Error fetching public keys: 401 Unauthenticated
I've verified that the Key ID, Issuer ID, and private key file are all correct, with the private key having admin access. The server time is correctly set to UTC. Given this, I can't identify what might be causing the issue. Any insights?
def generate_apple_developer_token():
# Load the private key in PEM format
with open(PRIVATE_KEY_FILE, 'rb') as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
# JWT header
headers = {
"alg": "ES256",
"kid": KEY_ID,
"typ": "JWT"
}
# JWT payload
payload = {
"iss": ISSUER_ID,
"iat": int(datetime.utcnow().timestamp()),
"exp": int((datetime.utcnow() + timedelta(minutes=10)).timestamp()),
"aud": "appstoreconnect-v1",
}
# Encode the header and payload as base64
header_base64 = base64.urlsafe_b64encode(json.dumps(headers).encode()).decode().rstrip("=")
payload_base64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
# Concatenate header and payload
message = f"{header_base64}.{payload_base64}".encode()
# Sign the message using ECDSA with SHA256
signature = private_key.sign(
message,
ec.ECDSA(hashes.SHA256())
)
# Convert the DER-encoded signature to raw format (r and s concatenated)
der_to_raw_ecdsa_format = lambda der: der[4:36] + der[-32:]
# Convert the signature to raw format (64 bytes)
signature_64 = der_to_raw_ecdsa_format(signature)
# Base64 URL-encode the signature
signature_base64 = base64.urlsafe_b64encode(signature_64).decode().rstrip("=")
# Concatenate header, payload, and signature to form the JWT
jwt_token = f"{header_base64}.{payload_base64}.{signature_base64}"
return jwt_token
def get_apple_public_keys():
try:
# Generate a fresh JWT
developer_token = generate_apple_developer_token()
# Set up headers with the authorization token
headers = {
"Authorization": f"Bearer {developer_token}"
}
# Fetch the public keys from Apple
response = requests.get('https://api.storekit.itunes.apple.com/in-app-purchase/publicKeys', headers=headers)
# Log the response if it's not successful
if response.status_code != 200:
print(f"Error fetching public keys: {response.status_code} {response.text}")
response.raise_for_status() # Raises an exception for 4xx/5xx errors
# Parse and return the public keys
response_data = response.json()
keys = response_data.get('keys')
if not keys:
print("No 'keys' found in the response from Apple.")
return []
return keys
except requests.exceptions.RequestException as e:
print(f"Error fetching Apple's public keys: {e}")
return []
Topic:
App & System Services
SubTopic:
Notifications
Tags:
App Store Server Notifications
App Store Server API