I'm facing an issue with Live Activity on the Apple Watch. I followed all the configurations outlined in Apple's official documentation, but during testing, I noticed inconsistent behavior. Some devices can display the Live Activity on the Apple Watch without any issues, while others can only see it on the iPhone, even though they are running the same system version. I've already checked the permissions, and everything is set up correctly, but I still haven't found what might be causing this difference. Has anyone experienced something similar or has any debugging suggestions?
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
Hi everyone,
I recently migrated my individual Apple Developer account to an Organization account for my company "". My Team ID remained the same. I'm now facing persistent issues with code signing and push notifications for my iOS app (Bundle ID: com.).
Current Problems:
"Untitled" Certificates in Xcode: When I go to Xcode -> Settings -> Accounts -> [My Apple ID] -> Select "" Team -> "Manage Certificates...", a number of my newly created Apple Development and Apple Distribution certificates are listed древ "Untitled". Some older ones are "Revoked". (See attached screenshot if possible).
"No App ID" for Push Notifications Console: In my app target's "Signing & Capabilities" tab, I've added the "Push Notifications" capability. However, when I click the info button to open the "Push Notifications Console", it states: "no app IDs: Register an App ID with the Push Notifications capability enabled to use the Push Notifications console." This is despite the fact that the Push Notifications capability IS enabled for my App ID com. in the Developer Portal, and I've configured an APNs Auth Key (.p8) for it.
Push Notifications Not Received (from Backend): While I can successfully send a test push notification directly from the Firebase Console to my device's FCM token, notifications triggered by my backend (Firebase Cloud Functions writing to a Firestore collection, which then triggers another function to send via FCM) are not being delivered to iOS devices. (Android seems to be working more reliably now).
Setup:
Using an APNs Authentication Key (.p8) linked to my Organization Team ID in Firebase Cloud Messaging.
Main App ID com. has "Push Notifications" capability enabled.
Notification Service Extension com..ImageNotification also has its App ID and Provisioning Profile set up for the Organization team.
Created new Development and Distribution certificates and Provisioning Profiles specifically for the Organization team.
Using "Automatically manage signing" in Xcode with the Organization team selected for both the main app target and the extension target.
Troubleshooting Done:
Revoked old/problematic certificates and profiles.
Recreated CSRs and new Development/Distribution certificates under the Organization team multiple times.
Recreated Provisioning Profiles.
Cleaned Derived Data in Xcode.
Ensured Bundle Identifiers are consistent.
Verified APNs Auth Key details (Key ID, Team ID) in Firebase.
I suspect there's a fundamental issue with how Xcode is recognizing or linking the signing assets for my Organization team after the account type change, despite the Team ID being the same. The "Untitled" certificates are a major red flag.
Has anyone encountered similar issues, particularly the "Untitled" certificates or the "No App ID" message for the Push Console, after an account migration or when working with Organization accounts? Any insights on how to resolve this would be greatly appreciated.
Thanks,
Benni
Topic:
App & System Services
SubTopic:
Notifications
Tags:
APNS
Provisioning Profiles
Signing Certificates
Hi Apple team and fellow developers,
We previously had Location Push Service Extension enabled and working in production. After transferring the app to a new Apple Developer team, the production App ID was transferred, but the Location Push entitlement was not retained.
We've also created a new App ID for development, and now need Location Push access enabled for both the transferred production ID and the new development ID.
We’ve already submitted the Location Push Access form with all relevant details.
Unfortunately, the App Transfer documentation didn’t make it clear that Location Push access would be lost, and now we’re blocked from making new builds — even for the existing production app.
❓ Questions:
Is it possible to re-enable Location Push for a transferred App ID?
What’s the expected timeline for entitlement approval?
Can Apple staff confirm the request status or let us know if any further action is needed?
Thanks in advance — this entitlement is critical for our app’s functionality and release pipeline.
Best,
Aidar
Topic:
App & System Services
SubTopic:
Notifications
Tags:
APNS
Developer Tools
Maps and Location
Developer Program
I need to decode a Base64-encoded receipt from an In-App Purchase and extract the transaction ID from it. However, I want to avoid using the verifyReceipt endpoint since it is deprecated.
Can anyone guide me on how to achieve this manually? Are there any specific libraries, steps, or code samples I should follow to parse the receipt data and retrieve the transaction ID?
Any help or insights would be greatly appreciated!
Topic:
App & System Services
SubTopic:
Notifications
Tags:
Subscriptions
In-App Purchase
App Store Server Notifications
App Store Server API
Hey there my application allows users to have video calls with each other using Agora. I have successfully set up incoming call functionality on Android but on iOS I am struggling to get the call ui to appear when the app is not running/in background/locked.
To my knowledge this is because there is much stricter security on iOS which is limiting me from calling this. When i initially set it up it worked at first when the app was in the background but I think I was failing to report the call to call kit in time and now it's not working.
I'm not sure if I need access to this entitlement:
com.apple.developer.pushkit.unrestricted-voip
Which i believe is only for the big boys or if I make sure I'm reporting the call to call kit fast enough that I won't encounter this issue and it will consistently work in the background.
Hello,
I am developing a calling service using CallKit and VOIP push.
I have occasionally encountered a strange issue.
The issue is that VOIP permanently fails to receive calls.
I was previously informed that even if the device is blocked, it can receive calls again after 24 hours.
Also, when I checked the device logic, it complied with the policy requirements set by Apple, including correctly calling CallKit's reportNewIncomingCall method.
Once the issue occurs, no matter how many times I try, VOIP does not receive calls, and neither a device reboot nor checking the Device Console Log shows any logs related to CallKit or VOIP.
I suspect this might be an issue with the VOIP token, and I believe that the only way to get a new one is to reinstall the app. Is that correct?
Of course, after reinstalling, it works fine again, but this is very inconvenient. I don't think this is the right solution.
Is there anyone who can share their insights on this issue?
Thank you.
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. All developers using APNs will need to update their 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.
We have modified the program as we received in the previous(thread 764479) issue.
Our program works very well and the notification problem has been almost solved in the test.
Then, we tested it in the user's environment.
At that time, one of the three iPhones stopped receiving notifications.
After 10 minutes, VoIP notifications were received again.
This device received PUSH notifications even when VoIP notifications did not come.
We must explain to the user why this incident occurred.
We would like to know if these three notifications were sent correctly to the device.
Also, is there any other way for us to deal with this other than improving the network?
[APNS LIST]Nov. 20th
could not receive(failed)
15:06:13 5793987C-D1A4-811F-917F-87DD7F5083B3
15:07:09 667E0A2F-43B5-37FC-2F2A-45A6C27EFC34
15:19:31 1353DF78-519E-B1DC-82B7-8B890E59FE37
received(success)
15:04:09 19CC1937-533A-9AF4-9472-41C839E461D7
15:35:00 CD23AC57-6EC7-4523-941F-B103EDB4DEFB
Hello,
I'm using Apple Wallet passes with a custom backend for distributing and updating them, as described in the documentation (https://developer.apple.com/documentation/walletpasses).
I'm sometimes seeing a behaviour where the device does not download an updated pass even though the push notification for informing about the changes has been successfully sent (I've received a success response from APNs).
APNs documentation says that it should retry sending the notification if the device is not reachable, but in the cases I'm describing here, the request from the device to fetch the updated pass never arrives. I don't have the apns-expiration header set. Also, I've checked the load balancer and firewall logs, etc. and there are no traces of the requests.
Any thoughts on what might be the issue here? Or how to debug this further?
token:1ac0f5ef2d37a0593f09e88be0f87daca27f23d4f7637fbc7a8102413d673bc3
msgId: 37d28693-16fe-0746-733e-a49d5879becc
send time: 2024-11-04 22:04:18.0(UTC+08:00)
response result: InternalServerError
这是什么原因呢?
self.pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
self.pushRegistry.delegate = self;
self.pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
//处理接收到的VoIP推送
(void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void(^)(void))completion
then we send message from our server or from apple's cloud service: https://icloud.developer.apple.com/dashboard/notifications website services:
when app is in foreground,withCompletionHandler wil be called correctly,but when app is in background or has killed ,withCompletionHandler not be called!!!
the background fetch、voice over ip is checked in signing & capabilities tabs
why?why?why?why?why?why?why?why?why?
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
Topic:
App & System Services
SubTopic:
Notifications
Tags:
APNS
User Notifications
PushKit
Push To Talk
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!
We have implemented Carplay in our voip based project and in this we have implemented Incoming call and chat notification feature for Carplay.
For Carplay we implemented siri.
Siri Object donated Successfully in Notification service Extension when notification didreceive method called.
Donation Code :-
func donateIncomingMessageIntent(sender: String, senderId: String, message: String, messageId: String, userInfo: [AnyHashable: Any],destination:String) {
// Create proper name components
clearAllinteraction()
var nameComponents = PersonNameComponents()
nameComponents.givenName = sender
//unknown
let senderPerson = INPerson(
personHandle: INPersonHandle(value: senderId, type: .unknown),
nameComponents: nameComponents,
displayName: sender,
image: nil,
contactIdentifier: senderId,
customIdentifier: "sender_\(senderId)"
)
let recipientPerson = INPerson(
personHandle: INPersonHandle(value: "me@example.com", type: .emailAddress),
nameComponents: nil,
displayName: "Me",
image: nil,
contactIdentifier: "me_id",
customIdentifier: "user_id"
)
let inMessage = INMessage(
identifier: messageId,
conversationIdentifier: "conversation_\(senderId)",
content: message,
dateSent: Date(),
sender: senderPerson,
recipients: [recipientPerson],
groupName: nil,
messageType: .text
)
let intent = INSearchForMessagesIntent(
recipients: [recipientPerson],
senders: [senderPerson],
searchTerms: [message],
attributes: .unread,
dateTime: nil,
identifiers: [messageId],
notificationIdentifiers: [messageId],
groupNames: ["Messages"]
)
let interaction = INInteraction(intent: intent, response: nil)
interaction.identifier = "message_\(messageId)"
interaction.direction = .incoming // Add direction
DispatchQueue.global(qos: .userInitiated).async {
interaction.donate { error in
if let error = error {
print("❌ Failed to donate INSearchForMessagesIntent: \(error.localizedDescription)")
} else {
print("✅ Donated INSearchForMessagesIntent successfully!")
let intentData: [String: Any] = [
"senderName": sender,
"senderId": senderId,
"message": message,
"messageId": messageId,
"timestamp": Date().timeIntervalSince1970,
"conversationId": "conversation_\(senderId)", // Add conversationId
"destination":destination
]
let defaults = UserDefaults(suiteName: "group.com.chatapp") // 🔁 Use your App Group ID
defaults?.removeObject(forKey: "lastCarPlayIntentData")
defaults?.set(intentData, forKey: "lastCarPlayIntentData")
defaults?.synchronize()
}
}
}
}
Here SenderID is like 3000@abc,2000@abc etc.
In siri ,When we handle INSearchForMessagesIntent at that time all data getting from Userdefaults because without Userdefaults INSearchForMessagesIntent value nil.
Even we enabled announcement using .allowAnnouncement.
We also tried to save same sender in contact Book because sometime siri search contact and not found then may be raise this type of issue.
So we need code level support for read incoming message in carplay when notification comes.
Thank you.
Here are some questions we received and answers:
Q1: Is there a limit to the number of alarms that can be scheduled using AlarmKit?
There is no set number as a limit, but this does not mean you can schedule a limitless number of alarms. Depending on device state, available resources, etc., the device may impose a limit, and restrict an app trying to schedule too many alarms simultaneously.
When you hit a limit and not able to schedule more alarms, you will receive the maximumLimitReached error.
Q2: Will the scheduled alarms persist after system or app events that may terminate an app, for example, a reboot, force quit, or app crash?
Yes, all alarms are expected to persist regardless of app or device state changes, once they are successfully scheduled.
Q3: Will alarms work if scheduled by an app that is hidden, or requires a passcode or Touch ID/Face ID to launch?
Hidden or passcode required apps do not work with AlarmKit. Currently, any scheduled alarms by such apps will silently fail.
Q4: When an alarm is dismissed (either by swiping or pressing the power button), can an app detect this action and execute code in response? What about force closed apps?
When an alarm is dismissed, the stopIntent set in the AlarmConfiguration is called.
Any code in the perform method of this AppIntent would execute.
Q5: Is there a focus mode that AlarmKit cannot break through?
No. AlarmKit alarms can break through all focus modes.
Q6: What is the expected behavior when alarms from multiple apps overlap? Which one gets priority?
Which alarm would get activated when multiple alarms are scheduled for the same time is non-deterministic. There is no way to guarantee which app or which alarm will "win".
Q7: What do pressing the physical buttons do when an AlarmKit alarm is active?
Any physical button that causes a reaction from AlarmKit will stop the currently alerting alarm.
Q8: If there are multiple alarms active at one time, which ones do physical buttons interact with?
Pressing a physical button will dismiss all currently alerting alarms
Argun Tekant /
DTS Engineer /
Core Technologies
Change History:
2025-08-15: First posted
Topic:
App & System Services
SubTopic:
Notifications
I am developing an app which makes use of actionable notifications.
On my code (the func userNotificationCenter function), I need to read my users from the local storage on the iPhone:
let query: [String: Any] = [
kSecAttrService as String: "uio-auth",
kSecAttrAccount as String: "users",
kSecClass as String: kSecClassGenericPassword,
kSecReturnData as String: true
]
var result: AnyObject?
SecItemCopyMatching(query as CFDictionary, &result)
let ref = result as? Data
But when the same code execute when I tap on the notification on the Apple Watch, it doesn't fetch anything. It now occurs to to me:
Does it mean that when an actionable notification programmed for the iOS is displayed on the Apple Watch, it tries to access its own storage, and not the iPhone? If so, is there a nice way to pass the values to the watchOS so that when the callback for the actionable notifications run, it has then the data it needs?
Ever since I updated the 18.1 I have noticed on both the Uber Driver app and Lyft Driver app that the banner notifications are on a three second delay when a ride notification comes in. These banner notifications have previously shown up immediately when a ride comes in and now it’s anywhere from 3 to 5 seconds before you see them.
I’m building a standalone Apple Watch smart alarm app that should trigger alarms on the watch in response to Bluetooth or internet events.
This means the app operates in the background and attempts to trigger an alarm when such an event occurs. As far as I know, the appropriate API for this is WKExtendedRuntimeSession.notifyUserWithHaptic:repeatHandler.
However, I can’t seem to start an extended runtime session while the app is in the background. I’m getting the following error:
-[WKExtendedRuntimeSession _invalidationReasonAndDelegateCallbackErrorForError:outCallbackError:]:729:
WKExtendedRuntimeSession hit internal error.
Error Domain=com.apple.CarouselServices.SessionErrorDomain
Code=17 "startSession cannot be called on a scheduled session"
UserInfo={NSLocalizedDescription=startSession cannot be called on a scheduled session}
Calling notifyUserWithHaptic directly also similarly fails.
It seems notifyUserWithHaptic is intended to be scheduled during a foreground session to trigger at a later time, rather than being called ad hoc from a background context.
Is there any way to create a proper alarm view on the Apple Watch from a background execution context?
Howdy,
I'm trying to figure out how to replicate the following behavior for our app:
The system is able to ascertain that the Mac equivalent of some iOS app is installed locally, and it prevents notifications from being mirrored. However, I am unable to determine how this association is inferred. When I check our iOS app under this prefpane, the switch remains enabled and toggleable—we'd like to act like Slack here.
My initial assumption is that an app group containing both the Mac and iOS apps can be used to create the association; however, I would like to confirm that this is indeed the case before doing so. I'm not terribly confident about this.
Details:
The bundle identifiers of both apps do not match. This also applies to Slack; its iOS app is com.tinyspeck.chatlyio while its Mac app is com.tinyspeck.slackmacgap.
In our case, the iOS app's identifier is like com.company.app while the Mac app's identifier is com.company.app.desktop.
Both apps are signed with certificates that have matching team identifiers. The com.apple.developer.team-identifier entitlement is present on the Mac app.
The Mac app shares a keychain access group with the iOS app.
The Mac app is not sandboxed.
The Mac app is an Electron app.
The Mac app does not use APNs. It sends notifications "locally".
I currently only have the iOS app installed on my iPhone via TestFlight, if that matters.
Notification mirroring does work, but we'd like to forcibly disable this by associating the apps together.
To my knowledge, the iOS app makes use of both a UNNotificationServiceExtension and a UNNotificationContentExtension.
The iOS app currently doesn't have an assigned category (at least in Xcode). The Mac app is currently miscategorized as a developer tool (LSApplicationCategoryType = "public.app-category.developer-tools";), but that should be fixed.
(Redacted) bundle information for the Mac app:
CFBundleDisplayName = App;
CFBundleExecutable = "App Desktop";
CFBundleName = App;
Note that our CFBundleExecutable differs from the bundle's display name/name because we're currently migrating our users to a new version of the app that they'd likely want to live alongside the new one. The filename of the bundle itself is, similarly, App Desktop.app.
For the iOS app, to my knowledge, the CFBundleName and CFBundleDisplayName are App.
I created a local notification as follows:
func scheduleNotification(title: String, subtitle: String = "", date: Date, id: String) {
// Extract the components from the date
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
let second = calendar.component(.second, from: date)
// Set the extracted components into DateComponents
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
let content = UNMutableNotificationContent()
content.title = title
content.subtitle = subtitle
content.sound = UNNotificationSound.default
let action1 = UNNotificationAction(identifier: Constants.NOTIFICATION_ACTION_IDENTIFIER_1.id, title: Constants.NOTIFICATION_ACTION_IDENTIFIER_1.label, options: [])
let action2 = UNNotificationAction(identifier: Constants.NOTIFICATION_ACTION_IDENTIFIER_2.id, title: Constants.NOTIFICATION_ACTION_IDENTIFIER_2.label, options: [])
let category = UNNotificationCategory(identifier: "reminderCategory", actions: [action1, action2], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
content.categoryIdentifier = "reminderCategory"
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
}
and I also have
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Handle foreground presentation options
completionHandler([.sound, .badge])
}
but for some reason the notification only shown on the phone. I've made sure that the phone is locked, apple watch is unlocked and also the notification setting in the watch app for this app is set to mirror.