Why aren't iOS10 user notifications firing? - ios

I've taken this code directly from Apple's page: https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent. I've place it in viewDidLoad(). UserNotifications has been imported.
It compiles, the app runs, breakpoints in the code are hit but no notification. I'm using Xcode 8 (not beta) and targeting iOS10.
Any idea what I'm doing wrong?
let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "Hello_message_body"
content.sound = UNNotificationSound.default()
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 2, repeats: false)
let request = UNNotificationRequest.init(identifier: "2", content: content, trigger: trigger)
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.currentNotificationCenter()
center.addNotificationRequest(request)

Test only on the device, and check your settings like crazy. In particular:
Be sure you've asked the user for authorization. If you have no authorization, you won't get any notifications for this app. If you never saw the authorization dialog, that's the problem here.
Even if the authorization dialog appeared and you tapped Allow, there are a lot of Notification settings that can prevent your notification alert from appearing in various places.
Be sure to look in the notification center. Do Not Disturb will turn off the sound and the alert, but it will appear in the notification center unless Notification settings forbid.
Be sure to give yourself enough time after center.addNotificationRequest to get out of your app, since unless you take steps to the contrary, the notification alert will not appear when your app is frontmost. Your intervals are pretty short.

Related

Removing Remote Notifications From Notification Center

I have a requirement to aggregate remote notifications of the same type.
example:
if a user received a push notification saying:"user 1 commented on your post", and then received "user 2 commented on your post", when receiving the second push I should remove the first notification and create a custom notification saying "2 users have commented on your post".
I'm getting the counter in the userInfo dictionary and I'm using NotificationService Extension in order to modify the notification's content.
the problem is I'm presenting 2 notifications:
"user 1 commented on your post"
"user 3 and 2 others have commented on your post"
instead of only the 2nd notification.
I've tried initializing UNNotificationRequest with custom identifier but still I'm getting double notifications (the original one and then the custom one).
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["push.comment"])
if let username = bestAttemptContent.userInfo["sender"] as? String,
let count = bestAttemptContent.userInfo["views_counter"] as? Int {
bestAttemptContent.title = "\(username) and \(count) others have commented on your post"
}
bestAttemptContent.body = "tap to see"
let request = UNNotificationRequest(identifier: "push.comment", content: bestAttemptContent, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
I tried using available-content : 1 in the notification's payload, but I'm not able to modify the notification when the app is terminated (not in background/foreground).
Basically I want a similar behaviour to facebook's messenger app.
Any Suggestions?
Push Notifications grouping is a feature that is provided in Android applications, but it is impossible to achieve the same on iOS. Because it should be handled by operation system(in other case it will be not possible to achieve when app is closed or minimized) and iOS doesn't provide this support.
So I read in Apple's documentation that when setting content-available : 1 in the aps object it launches the app in a background mode and its possible to handle the received silent push.
its important to avoid setting the mutable-content : 1 and add background modes with remote notifications on in the apps configurations.

Push notification works only when app launched with Xcode

I have a big problem, I set up (with great difficulty) push notifications on my iOS project. I decided to receive the data of the notification in the "didReceiveRemoteNotification" method of the "AppDelegate" then to create it programmatically (in order to carry out mandatory personal treatment). Everything works perfectly, only when I launch my application without the help of Xcode, I no longer receive the notifications, the notification creation code is not executed. I do not know what to do ...
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping
(UIBackgroundFetchResult) -> Void) {
let body = userInfo["body"]
print(userInfo)
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.body = body! as! String
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:
1, repeats: false)
let request = UNNotificationRequest(identifier: "idt", content:
content, trigger: trigger)
UNUserNotificationCenter.current().add(request,
withCompletionHandler: nil)
} else {
// Fallback on earlier versions
}
completionHandler(UIBackgroundFetchResult.newData)
}
Thanks you very much
When you launch your app from a notification you need to check the launchOptions in application:didFinishLaunchingWithOptions: to see if UIApplicationLaunchOptionsRemoteNotificationKey is present.
According to the Documentation:
The value of this key is an NSDictionary containing the payload of the remote notification. See the description of application:didReceiveRemoteNotification: for further information about handling remote notifications.
This key is also used to access the same value in the userInfo dictionary of the notification named UIApplicationDidFinishLaunchingNotification.
Once you determine that the launch contains a notification, invoke your notification handler method with the notification payload obtained from launchOptions.
What you have now, which is application(_:didReceiveRemoteNotification:) is only triggered when the app is already running:
If the app is running, the app calls this method to process incoming remote notifications. The userInfo dictionary contains the aps key whose value is another dictionary with the remaining notification
You need to check in your project settings/Capabilities - Background Modes - Remote notifications
Enable Remote notifications in Capabilities.
{
"aps" : {
"content-available" : 1,
"badge" : 0,
"Priority" : 10
},
"acme1" : "bar",
"acme2" : 42
}
The notification’s priority:
10 The push message is sent immediately.
The remote notification must trigger an alert, sound, or badge on the device. It is an error to use this priority for a push that contains only the content-available key.
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/BinaryProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH13-SW1
When the device is running and connected to Xcode, the system treats silent notifications as high-priority simply because the OS is smart enough to know "You must be debugging your app, so I will treat your app's tasks as high priority".
When the device is disconnected from Xcode, the system then treats silent notifications as low-priority. Therefore, it doesn't guarantee their delivery in order to improve battery life.

How to Schedule unclearable or non-removable Local Notification?

I want add simple local notification which unclearable for particular time. like 10 minutes you can not clear it. if solution is possible through other way suggestion appreciated.
Anyone having idea about it?
what you can do is when you are dismissing all pending notification reset the particular notification again or you can remove other notifications by their identifier and keep the particular notification
here is the code to fetch all pending notifications.
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { requests in
print(requests)
for request in requests {
srrNotification.append(request)
print(request)
}
})

iOS: Do something when a UserNotification is received?

Is it possible to do something when the UserNotification message is delivered to the user every time?
let tdate = Date(timeIntervalSinceNow: 10)
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: tdate)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let identifier = "hk.edu.polyu.addiction.test"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if error != nil {
debugPrint("center.add(request, withCompletionHandler: { (error)")
} else {
debugPrint("no error?! at request added place")
}
})
This is the code i did to deliver a notification when the user press a button. (i.e., after 10s, the notification appear to the user.)
Even the user not press on the notification, i want some variable of the app updated (assume the app is at the background).
Possible?
Or, as long as this notification is done. another new notification is scheduled, according to some calculations in my app, possible? (not fixed time, cannot use repeat)
Yes, it is possible! Need to modify the capabilities :
Enable background fetch in background mode.
Enable remote notification in background mode.
Implement delegate method : application:didReceiveRemoteNotification:fetchCompletionHandler:
This delegate method gets called when the notification arrives on the phone, so you can refresh your data.
When user taps on notification delegate method: didReceiveRemoteNotification
gets called and opens the app and user will get latest data in the app.
Apple API reference:
If your payload is not configured properly, the notification might be
displayed to the user instead of being delivered to your app in the
background. In your payload, make sure the following conditions are
true:
The payload’s aps dictionary must include the content-available key
with a value of 1. The payload’s aps dictionary must not contain the
alert, sound, or badge keys. When a silent notification is delivered
to the user’s device, iOS wakes up your app in the background and
gives it up to 30 seconds to run.

CloudKit Not Sending Update Notifications

I am trying to develop a simple messaging app to learn the basics of CloudKit.
I've got it almost figured out, except I am not able to receive notifications for record update events.
To test the app, I am running it simultaneously on the device and on a simulator.
Both instances are logged into the same iCloud account (haven't gotten around to create a dedicated account for testing...); however the app distinguishes the local user from the remote one using UUIds, so that is not a problem.
When one instance of the app wants to send a message, it creates a record and saves it to CloudKit.
I am aware that APNs is not supported on the Simulator, but if I send a message from the Simulator I can get notified on the device.
This works.
Next, I want to mark the messages as "read": That is, flag them when they are first displayed on a device that is not the one that authored them.
I do this by fetching the corresponding record, modifying it, and saving it. So, the message I sent from the device is displayed on the simulator, and flagged there as 'read'. I sync that change with cloudKit and expect the device to receive a notification:
publicDatabase.perform(query, inZoneWith: nil, completionHandler: {(records, error) in
guard let records = records, records.count > 0 else {
return print("Error - Message: \(message.text) by \(message.userName) NOT found on the cloud!")
}
let record = records[0]
// HERE THE RECORD IS MODIFIED LOCALLY:
record["readTimestamp"] = (message.readTimestamp! as NSDate)
// Now, save it:
self.publicDatabase.save(record, completionHandler: {record, error in
guard error == nil else {
return print("Error - Message: \(message.text) by \(message.userName) could NOT be saved as read!")
}
print("Message: \(message.text) by \(message.userName) SAVED as read at \(message.readTimestamp!)")
})
})
However, on the other end, the 'Update' notification is never received.
Is it because both instances are logged into iCloud as the same user? I find this hard to believe, since the "Create" notifications are delivered without problems.
Subscriptions for both notifications ("Message Create" and "Message Update") are registered successfully and appear listed on the CloudKit Dashboard (triggers INSERT and UPDATE).
Update: After a long time thinking what can possibly be different between my "create" subscription and my "update" subscription that could cause only one of them to fire a notification, I realized that only the "create" subscription had a notification body:
let subscription = CKQuerySubscription(recordType: "Message",
predicate: NSPredicate(value: true),
subscriptionID: Bundle.main.bundleIdentifier! + ".subscription.message.create",
options: .firesOnRecordCreation
)
let notificationInfo = CKNotificationInfo()
// THIS LINE MAKES ALL THE DIFFERENCE:
notificationInfo.alertBody = "You've Got Mail!"
subscription.notificationInfo = notificationInfo
publicDatabase.save(subscription, completionHandler: {savedSubscription, error in
...whereas the "update" subscription did not:
let notificationInfo = CKNotificationInfo()
subscription.notificationInfo = notificationInfo
Once I added an alert body, the "update" notifications started arriving.
However, this is just a workaround: I need silent notifications for my read updates. It doesn't make sense to display a banner just to alert the user that his message has been read on the other end.
Also, the CloudKit programming Guide does not mention this limitation.
Is there a way to subscribe with silent (i.e., empty) push notifications?
Update 2: Actually, I found this bit on the API Reference for CKNotificationInfo:
Note
If you don’t set any of the alertBody, soundName, or shouldBadge
properties, the push notification is sent at a lower priority that
doesn’t cause the system to alert the user.
(emphasis mine)
I still fail to see how this "lower priority that doesn’t cause the system to alert the user" is equivalent to "application(:didReceiveRemoteNotification:fetchCompletionHandler:) not being called at all".
The solution appears to be to use an info object with shouldSendContentAvailable = true, like this:
let info = CKNotificationInfo()
info.shouldSendContentAvailable = true
subscription.notificationInfo = info
That has solved it for me. It causes didReceiveRemoteNotification: to fire, without any user visible notification appearing. So it's a silent notification, as desired, and it's actually arriving, as desired.
If I leave subscription.notificationInfo nil the app is never notified of changes. But with an [effectively silent] info object I get the desired results.

Resources