UNUserNotificationCenter.add not finishing in iOS Share Extension - ios

My iOS app has a share-extension where users can also upload Attachments.
As those can be large, the upload is done using an URLSession with URLSessionConfiguration.background. After the upload is done, I'd like to show the user some kind of success-ui and chose a Notification for that purpose. So now in my completion block I am doing something like that:
let content = UNMutableNotificationContent()
content.body = "Success"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
print("This line is never called")
and as you can see in my sample code here, the app is stuck ad center.add(request). This method is just never completing?!? When calling it, I am on the main-thread, but also tried on other threads... always the same result
Does anybody have an idea why?

Related

Triggering several notifications in Apple Watch in short period of time makes them grouped

Im making a standalone Apple Watch app, testing on device, and its meant to play several bells with vibration (app can be closed and alerts should play) in a period of like 5 seconds or so, Im using local notifications for this and no matter what I try I only hear the first notification bell or if I extend in time maybe 2 bells, in the past alerts summary these consecutive notifications are listed but the bells are not played. I know there is a way to do this as I saw an app that plays several bells like this and is standalone Apple Watch app too. Im using swift, how can I do that? Thanks for any help
I made a separate code only to trigger some alerts in 10 seconds from now to show better my issue here:
import SwiftUI
import UserNotifications
struct ContentView: View
{
var body: some View
{
VStack
{
Button("Request Permission")
{
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success {
print("All set!")
} else if let error = error {
print(error.localizedDescription)
}
}
}
Button("Schedule Notification")
{
let content = UNMutableNotificationContent()
content.title = "First notification"
content.subtitle = "Whatever"
content.sound = UNNotificationSound.defaultCritical
// show this notification 10 seconds from now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
//----------/
var content2 = [UNMutableNotificationContent](repeating: UNMutableNotificationContent(), count:100)
var trigger2 = [UNNotificationTrigger](repeating: UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
, count:100)
var request2 = [UNNotificationRequest](repeating: UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger),count:100)
// add notification request
UNUserNotificationCenter.current().add(request)
for i in 0..<100
{
content2[i] = UNMutableNotificationContent()
content2[i].title = "Chained notifications"
content2[i].subtitle = "whatever"
content2[i].sound = UNNotificationSound.defaultCritical
//content2[i].interruptionLevel = .active
content2[i].interruptionLevel = .critical
content2[i].categoryIdentifier="category\(i)"
content2[i].threadIdentifier="asadasaa\(i)"
trigger2[i] = UNTimeIntervalNotificationTrigger(timeInterval: 10+Double(i/4), repeats: false)
// choose a random identifier
request2[i] = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request2[i])
}
//-----------/
}
Button("Stop")
{
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I tried several intervals between notifications, making them more separate or closer to each other and only first one plays or 2 or more bells if there is some longer intervals but most are grouped and only hear like one every second at the most I think, I read somewhere these are meant to be payed in 0.9 seconds at the shortest time but as said I have seen an app able to do this so there has to be a way
I was suggested to use different thead or so, but didnt work, tried other parameters of this too like to change revelance or so but nothing worked
The issue may work the same in iPhone if you are more familiar with it, so if you know a workaround for this let me know

Delay UNLocationNotificationTrigger on UNNotificationRequest?

I have properly set up location based local notifications. As of now the user receives a notification when they enter a defined zone (CLCircularRegion). Id like to delay that notification about 10 minutes after they enter the zone, could that be possible?
// SENDING WITH (UNLocationNotificationTrigger)
let trigger = UNLocationNotificationTrigger(region: destRegion, repeats: false)
let request = UNNotificationRequest(identifier: notificationInfo.notificationId,
content: notification,
trigger: trigger)
UNUserNotificationCenter.current().add(request)
I also send notification locally for other reasons at different places in my app. This causes a delay for the elapsedSeconds.
// SENDING WITH (UNTimeIntervalNotificationTrigger)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: elapsedSeconds, repeats: false)
let request = UNNotificationRequest(identifier: "cartabandon", content: localnotification, trigger: trigger)
UNUserNotificationCenter.current().add(request)
Maybe theres a way to combine the two? Or another option?

iOS - Trigger Notification Service Extension through Local Push Notification?

Is it possible to trigger Notification Service Extension through Local Push Notification?
My code snippet
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
let aps = ["mutable-content": 1]
let dict = ["aps": aps, "some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
No, It is not possible to trigger notification service extension through push notification.
Reason: Service extension lets you customize the content of a remote notification before it is delivered to the user. e.g decrypt the message or download the attachments
but I personally think there is no point of downloading the notification content attachments in service extension because you can always download the attachments before scheduling. e.g
// Download attachment asynchronously
downloadAttachments(data: data) { attachments in
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
// Add downloaded attachment here
content.attachments = attachments
// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
// No need of adding mutable content here
let dict = ["some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Let me know if you have different use case.
Pleas read the documentation before posting. The first line states:
A UNNotificationServiceExtension object provides the entry point for a Notification Service app extension, which lets you customize the content of a remote notification before it is delivered to the user.

How to keep UNUserNotificationCenter sound playing until user stops it

There are a few articles that address this same problem, but (from what I've seen) they're all from 4 years ago and in Objective-C. I'm working with Swift 4.2.
I'm making a countdown timer app. While the app is in the background and a timer expires, I want the notification sound to keep playing until the user stops it by tapping on the notification.
So far, what I have only plays an alert sound once from the background/lockscreen.
Here is the method I am working with.
func notifications(title: String, message: String){
center.delegate = self
let restartAction = UNNotificationAction(identifier: "RESTART_ACTION", title: "Restart timer", options: UNNotificationActionOptions(rawValue: 0))
let stopAction = UNNotificationAction(identifier: "STOP_ACTION", title: "Stop", options: UNNotificationActionOptions(rawValue: 0))
let expiredCategory = UNNotificationCategory(identifier: "TIMER_EXPIRED", actions: [restartAction, stopAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0))
// Register the notification categories.
center.setNotificationCategories([expiredCategory])
let content = UNMutableNotificationContent()
content.title = title
content.body = message
content.categoryIdentifier = "TIMER_EXPIRED"
content.sound = UNNotificationSound(named:UNNotificationSoundName(rawValue: _currentTimer.getSoundEffect+".mp3"))
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(_currentTimer.endTime), repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
So, the answer I'm going settling on with this question is that there is no answer. Apple does not want third party developers playing notification sounds for longer than 30 seconds in any circumstance, even if it is to build a timer app. Their timer in the Clock app will go off until you silence it, but third party developers aren't allowed to do that.

How to show multiple local notifications

Background:
Im writing an application where a bot sends you messages. These messages can be received as local notification.
The Problem:
When the bot sends multiple notifications within a short span of time (1 second between each message), the notification center will only show one message. I will hear the notification sound every time I expect to, But i will still only see the first message.
Relevant code:
func postUserNotification(content: String, delay: TimeInterval, withDictionary dictionary: [String:String] = [:]) {
let notificationContent = UNMutableNotificationContent()
notificationContent.body = content
notificationContent.userInfo = dictionary
notificationContent.categoryIdentifier = "message"
let dateAfterDelay = Date(timeIntervalSinceNow: delay)
let dateComponents = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: dateAfterDelay)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let identifier = "identifier" + "\(NotificationManager.incrementor)"
let localNotification = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(localNotification){ (error : Error?) in
if let theError = error {
print("the error is \(theError.localizedDescription)")
}
}
}
Nothing wrong with your code :
Like you wrote in your question, this is mentioned in the Apple Docs:
If you are sending multiple notifications to the same device or
computer within a short period of time, the push service will send only
the last one.
https://developer.apple.com/library/content/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG23

Resources