Swift 3 - Turn off badge, alert, sound - ios

I've read a lot of answers here and I can't find answers of this questions
How to stop badge, alert and sound from notifications when the application is not running ?
How to stop badge, alert and sound from notifications when the application is in Background?
in this function:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void)
I've put completionHandler([]) without [.badge, .alert, .sound] and I still receive notifications in background when the app is runned.
Also I have function in my code that sends notification when somebody is typing to you and you see that he is typing to you when you are in-app, but when the application is not runned you are receiving notification with badge alert sound? How to prevent that?
PHP Code:
$body['aps'] = array(
'content-available' => 0,
'typingNewMessage' => 'true',
'senderId' => $your_id
);

Two things first: Are you using websocket/socket.io for the chat in your app? And as for notifications, have you set up remote notifications in background modes?
Background modes.
Read up on the docs for push notifications, it sounds like you're adding steps here, or missing some. Basically as kathayatnk mentioned, his method should give you what you want. So if you haven't activated remote background notifications:
To configure your app to process silent notifications in the
background
In the Project Navigator, select your project.
In the editor, select your iOS app target.
Select the Capabilities tab.
Enable the Background Modes capability.
Enable the Remote notifications background mode.
If this is done, you should receieve them in the background..
Also, you are using the wrong method for recieving background notifications in the background.. As stated in the same link above:
In iOS, the system delivers silent notifications by calling the
application:didReceiveRemoteNotification:fetchCompletionHandler:
method of your app delegate. Use that method to initiate any download
operations needed to fetch new data.
how i usually use it :
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
guard let aps = userInfo["aps"] as? [String:Any] else {
//handle something here..
return
}
//handle the content here...
}
You can also perform background tasks from inactive states here by playing with the return value of completionHandler. I suggest you read up on it too.
For your chat issue...
Clarify how you're performing this...
If you're using a websocket/socket.io architecture:
I would strongly recommend not using notifications to notify a user of anything with APNS when using a websocket. Websockets are very efficient and much quicker. Handling both can greatly complicate things. Stick to the socket approach, and use a method server side that checks if a user is still within the app. Something like a ping-pong method like here. Have that method switch to APNS delivery when the socket client ping method shows that the user has left the app or has closed it. This means, if the user is still in the app, but not in the conversation, stay with the ping approach but program the UI response differently (take FB Messenger or Snapchat's notification tabs for example).
If you are not using websockets/socket.io:
...Switch to websockets technologies or packages (depending on your server platform type) or socket.io or use firebase realtime chat services.
Let me know your setup like i asked earlier, but if youre doing all of this already and still getting the issues, then post your code.
Personnaly, i've used RawWenderlicht for APNS guides for over a year, good stuff if you ask me.

To silent push notification the payload should contain content-available key as:
{
"aps": {
"content-available": 1
}
}
Also, you need to enable Remote Notifications in Background Modes under Capabilities setting of your Xcode project.
Now your app will wake up in the background when it receives one of these push notifications.
didReceiveRemoteNotification will be called in AppDelegate whenever the push notification is received.
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
let aps = userInfo["aps"] as! [String: AnyObject]
if aps["content-available"] as? Int == 1
{
//Your code
}
}
For more on how to handle push notifications in foreground/background refer to: https://www.raywenderlich.com/156966/push-notifications-tutorial-getting-started

you can add silent push notifications (set content-available key appropriately) when sending pushes, like below.
//when you want the badge and sound
aps {
content-available: 1
}
//When you want silent notifications
aps {
content-available: 0
}
This will call the appropriate delegate method but wont display badge and sound

Related

Do FCM silent push notifications (Background push) in iOS work as defined by Apple?

I am planning to implement silent notifications via FCM in my iOS app. I found many articles and SO posts describing how to achieve this. But my question stems from the fact that I found this code snippet in the FCM documentation. Please note the first line of the comment.
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult)
-> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
This code is provided under the heading Handle silent push notifications. As per my understanding, silent notifications do not appear on the screen or alert the user in any way, no matter in what state the app is in. Then why is there a mention about tapping the notification ?
My intention is to send a silent notification to the iOS device and perform some background task without any user interaction. The limitations of background notifications are acceptable. As I do not currently have the permissions to a apple developer account to test this out, could any one tell me if this can be achieved with FCM ? Or should I consider using APNS directly ?
The system calls this method when your app is running in the foreground or background, thats why the comment is there. In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a remote notification arrives. However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.
You can also achive by using FCM To send a background notification, create a remote notification with an aps dictionary that includes only the content-available key, as shown bellow. You may include custom keys in the payload, but the aps dictionary must not contain any keys that would trigger user interactions.
{
"aps" : {
"content-available" : 1
},
"acme1" : "bar",
"acme2" : 42
}
The comment inside the code snippet is old and wrong see the apple latest explanation about the method

Obtain contents of remote push notification received while the app is not running after user launches the application from app icon

I was following Apple docs and some other sources. But can't find the answer.
Problem is as follows:
Conditions:
The remote push notification the app is receiving is time sensitive, and should be delivered to the device ASAP.
Notification contains information which is required whichever way the user launches the app (i.e. whether they click on notification or not).
Scenario:
Remote push notification is sent to a device while the app is not running (not on background, but not running at all).
User doesn't click on notification. Instead, user clicks on app icon.
It appears that in this case there's no way to receive notification contents upon application startup. Notification is not lost: it stays inside notification area until user clicks on it, but notification contents are not provided to the app upon app startup.
What did I try so far
I was able to get notification contents in every other scenario:
I have a handler
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler <...>
for when the app is in foreground
When app is in background, the handler
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: <...>
As a safeguard, I also loop through outstanding notifications like this:
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions <...> {
UNUserNotificationCenter.current()
.getDeliveredNotifications {
(notifications: [UNNotification]) -> Void in
And, in the same function I am checking if launchOptions contains any notifications.
With this combination it looks like I'm able to cover every single scenario, except for the case I outlined above. That is: when user clicks on app icon while app is not running after notification was delivered:
didReceiveRemoteNotification:fetchCompletionHandler is not called
UNUserNotificationCenter.current().getDeliveredNotifications returns 0 notifications (although notification is visible in notification area).
In didFinishLaunchingWithOptions the value of launchOptions is alos nil...
This article seems confirms this behavior, but doesn't provide any solution.
I also saw this question, but although it may be that acceptable solution for OP's needs, it does not provide a direct answer to his question, since using content-available flag changes how notification is delivered (see Configuring a Background Update Notification section on this page, and also reduces its priority, as explained in apns-priority section of this page.
BTW if I click on notification after opening the app, the behavior is as expected, so notification is not completely lost to the app, it's just not provided on its launch.
So what am I dealing with here? some edge case, bug or maybe such behavior is intended? if so, why?
Thanks in advance.

APNS: Receive silent Remote Notification if app was force quit

I am looking desperately for a way to receive silent remote notifications when the user has force quit his app.
I already experimented with this a while ago.
The only way to do that, was to remove the content-available flag. But then it wasn't a silent notification anymore. The main use case was to download additional content to the remote notification and only then schedule a local notification in turn.
As the new UNNotification Framework was introduced they also introduced the new Notification Service Extension which provides an elegant way to download content corresponding to a remote notification.
But there is still no way to do the same with silent notifications when the app is force closed. Or did I miss something ?
PS: Maybe it is a duplicate, but other threads do not respect the Notification Service Extension.
When app force closed. AppDelegate method:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
}
will not called. But if your json payload contain aps you will see instant message, after you swipe (or click on notification) method will be called.
You can look google and find table of difference silent and normal state and their work in other Application State
Finally I found the answer in localisation also discussed here:
Change language of alert in banner of Push Notification
I also use the new Notification Service Extension in combination to alter content before the notification is delivered.

getting silent push notification

I am trying to receive silent push notification when the app is totally off, but I'm not getting the push, what am I missing?
I added in split: Required background modes -> App downloads content in response to push notifications
I implement in the AppDelagate:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.NewData);
JLToast.makeText("background").show()}
I send a push:
aps
{
content-available: 1
}
When the app is in background, I get the silent push notification,
but when the app is out of background (totally shot down),
I don't get the push.
What is missing?
As far as I know, silent push notification won't work in case the app is forced quit (by user). Consider 2 cases:
Force quit (by user, removing app from running apps list): app won't get notifications
Not force quit (Eg: when user restarts the phone, the app will be closed but it's not considered as being forced quit by user): the app will be launched in background mode and receive notifications

Execute code in background when push notification is received

I'm trying to find out what is actually possible on iOS when it comes to background tasks.
I have an app which is running in the background and tracking location changes on the device.
Now, is it possible to send a push notification to the device and have the device send the current location to a server without needing the user to open the app so it runs in the foreground?
I know this question is a bit old but I'm answering for those who, like me, arrived here long after the question was asked.
Now, is it possible to send a push notification to the device and have the device send the current location to a server without needing the user to open the app so it runs in the foreground?
Yes. You can now do that. I'm currently doing something pretty similar in my app. There are some other SO questions that now correctly state this. This is one
Basically, you have to enabled Background Execution for Remote Notifications. You can do this in XCode by going to your app's target. Open the Capabilities tab enabling the Background Modes feature and checking the Remote Notifications item in the checklist. (I'm assuming you already have enabled the Push Notifications feature).
With this the code you use to handle notifications in foreground will also serve you in background as
the application:didReceiveRemoteNotification:fetchCompletionHandler method will be called while your app is in background.
Here's a sample code in Swift 3.0:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
You may wanna check out this SO question (and accepted answer) about how to handle network request in background. Background request not execute Alamofire Swift
Check out the docs about Background Execution. Particularly the section about Push Notifications
Unfortunately I don't think so. When your app is in a suspended (freezed) state, push notifications are managed by SO, users need to reopen the app. They other way around is to create local notification for significant changes, when the notif arrives your app has a minimum amount of time, it will be not enough to post data, but you can study something. I will suggest you to read this question it talks about bluetooth and geolocation link
It's impossible. This OS has one principle —— user should know what you(your app) have done. When your app is suspended,your push message will be received by the notification center.The only way let your app know this thing happened is to launch your app through the notification center.so.....

Resources