How to set sound for push notifications in ios objective c? - ios

I am working on an app in which I have implemented Apple push notifications. When my app is in background state then I am able to receive push notifications without sound but when my app is in active state then I am able to get sound for notifications but not showing any banner for it.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateInactive)
{
AudioServicesPlaySystemSound(1007);
}
else {
AudioServicesPlaySystemSound(1007);
carPlateNo = [userInfo valueForKeyPath:#"aps.alert.loc-args"];
if(![carPlateNo isEqualToString:#"Return Message"])
{
[self receiveServices];
}
// Push Notification received in the background
}
}
Can anyone help on this?

You have to set sound in APNS Payload only, and add sound clip in XCode bundle.
Sample Payload
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
More Info

Try This :
when you send push notification, just add the name of sound in JSON payload. Example:
{
"aps" : {
"alert" : "your alert message here.",
"badge" : 1,
"sound" : "samplemusic.aiff"
}
}
Thats it! You don't have to do anything special in code of app.

iOS takes care of delivering notification to app when app is killed. iOS also takes care of showing the banner/alert depending on user settings and also plays the audio for the notification.
What you can do though is specify what audio to play in your notification payload
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
If you don't want default notification sound you can bundle your own audio file of format .aiff and ship it with app and specify the file name in your notification payload as shown above
refer : https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
As far as
when my app is in active state then I am able to get sound for
notifications but not showing any banner for it
concerned, when your app is in foreground its your app's responsibility to show any custom banner/alert. System default banner/alert will not be displayed. You can use https://github.com/sandeeplearner/SBNotificationBar for the same :)

- When my app is in background state then I am able to receive push
notifications without sound
There must be one the following two issues
1.Sound key is not there or sending empty value for it in payload (Reference)
2.Your phone in silent mode
- my app is in active state then I am able to get sound for notifications but not showing any banner for it.
When Application is active app is responsible to handle what to do on push notification receive for more please refer this answer

Related

IOS: How to support old apps while adding a localisation to push notification

I would like to add new push notification to my app. It would have a localisation so lets imagine it looks like this.
{
"aps" : {
"alert" : {
"loc-key" : "localization_key",
}
}
}
The version that will have this localization_key inside of .strings file is V2.
How do i handle this notification on V1 that is already on the app store, as the push notification my user will see will have "localization_key" as body

In swift remote notification is there a way to display a different message in the banner other than the one received from server when app is killed?

If my payload from the server is
{ "aps" : { "alert" : "You got a mail";
"badge" : 0;
}
"user": { "name" : "Nicole" } }`
And It also gives me some other data about the name of user who sent it . Is there a way to display custom message in the format : "Nicole sent a mail" in the notification center or banner ?
It is possible since iOS 10 by creating a Notification Service Extension. You can check the documentation for its details. Also, here is a good tutorial from Avanderlee that explains how to add Notification Service Extension to you app.

React native ios handle push notification without clicking on notification

I am using react-native 0.60, Firebase push notification. I need help with react native firebase ios push notification with data payload.
I am able to send notifications with data payload. I am able to receive the notification when the app is foreground, background, killed. I am sending data with notification.
{
"to" : "FCM Token",
"show_in_foreground" : "true",
"collapse_key" : "type_a",
"notification" : {
"notification_type" : "N",
"ad_type" : "banner",
"sub_type" : "info",
"text_message" : "Lorem ipsum dolor sit amet",
"Title": "Notification 0000",
"image_url": "https://firebasestorage.com/xyz",
"ad_time" : 7,
"x_time" : 4,
"delay_time" : 4
},
"data" : {
"notification_type" : "N",
"ad_type" : "banner",
"sub_type" : "info",
"text_message" : "Lorem ipsum dolor sit amet",
"Title": "Notification 0000",
"image_url": "https://firebasestorage.googleapis.com/xyz",
"ad_time" : 7,
"x_time" : 4,
"delay_time" : 4
},
"content-available" : true,
"priority": "high"
}
I want to show notification and also store data in local app database at the same time even if the user doesn't click on the notification.
I am able to handle the notification when user clicks on the notification. I want to update the data in the app when the notification is received by the user and also show the notification. I dont want to use silent background notification.
My Appdelegate code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
if ([[FIRAuth auth] canHandleNotification:userInfo]) {
completionHandler(UIBackgroundFetchResultNoData);
return;
}
[[FIRMessaging messaging] appDidReceiveMessage:userInfo];
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
NSLog(#"Inactive - the user has tapped in the notification when app was closed or in background 3");
}
I want to achieve
1. User should get the notification even if the app is closed, killed, background.
2. User's App local Database should be updated even if user doesnt click on the notification.
I have achieved the first point looking for 2nd. I am new to react native. I know that when the notification is received the completion handler method is called. when the app is killed nothing is showed in the xcode log. how do i write code in completion handler method ? and how do i check if the method is called and task is performed.
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
navigation.navigate(remoteMessage.data.type);
});
// Check whether an initial notification is available
// This will handle notification when App is opened from killed state or background
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
}
setLoading(false);
});
Use this notification listeners
2nd thing React-Native Does not can not manage kill state for Application. Because when Application is killed, js engine shuts down.
3rd: v6 lib does not support badge count updating like v5 did. So When there are notification and When User Directly Open Application all notification should be cleared,
So that can be done from Native Side
For Android -> MainActivity.java
#Override
protected void onResume() {
super.onResume();
// Clear all notification
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
}
So This Will Clear All Notification From StatusBar, LockScreen, whenever app is opened whether directly or from Notification Press. But still do this if requirement is this.
On more thing Android manages badge count and update automatically, but for iOS Native Code implementation must. in AppDelegate file.
Most common mistake seen : remoteMessage.notification and remoteMessage.data both are different, console whole remoteMessage object :)))
So, in iOS currently, there are no background services that could be run on the background as we have it on Android. So, from my perspective, you can't check were notification shown or not to the user in realtime if the app was killed. I can't understand why you need that. Notifications act pretty much correctly, so, you don't need to check iOS is it works.
What you can do is collect information about notifications after your app restarts.
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
YOUR_NAVIGATION_PATH_HERE;
});
SOURCE : https://rnfirebase.io/messaging/notifications

IOS Push Notification count

I need to display push notification count. when user launches the application by tapping application or from notification bar.
Example: application is in background and device received 10 notifications related to my app. we have to display notification count 10 within app.
I can achieve this by adding content-update key in notification payload. But I don't want to make change in notification payload.
Your backend need to send bagdes for this :- Eaxmple
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
and you can use this badges in your apps.
You can check how many notifications were received (assuming you are incrementing badges in your push notifications) by checking [UIApplication sharedApplication].applicationIconBadgeNumber.
This also assumed you reset the badge count each time they leave the app (standard practice), if for some reason you don't though, simply save [via NSUserDefaults] the current badge count in the willResignActive callback and check the delta when they return.

is it possible to send a push notification without using the alert attribute in a json using iOS?

I am trying to send a json format which doesn't have an "alert" attribute. The thing is, when I try to remove the alert attribute, the notification won't appear. Is there any way I can handle this? Thanks in advance
P.S I've tried to use action, however it still doesn't show up (I think this is only possible in android)
Yes, you can do it. It is possible to send a push notification without an alert. You can even register your application just to badge notifications, in which case the provider server won't even be able to send alerts or sounds.
The Notification Payload
Each push notification carries with it a payload. The payload specifies how users are to be alerted to the data waiting to be downloaded to the client application. The maximum size allowed for a notification payload is 256 bytes; Apple Push Notification Service refuses any notification that exceeds this limit. Remember that delivery of notifications is “best effort” and is not guaranteed.
For each notification, providers must compose a JSON dictionary object that strictly adheres to RFC 4627. This dictionary must contain another dictionary identified by the key aps. The aps dictionary contains one or more properties that specify the following actions:
An alert message to display to the user
A number to badge the application icon with
A sound to play
Note that it says one or more of the properties. The alert property is optional. You can even send a notification with an empty aps dictionary (i.e. send only custom properties).
The following example shows an empty aps dictionary; because the badge property is missing, any current badge number shown on the application icon is removed. The acme2 custom property is an array of two integers.
{
"aps" : {
},
"acme2" : [ 5, 8 ]
}
The only alert the user will see it the alert that asks him/her whether to allow push notifications. That alert will only be displayed the first time the app is launched after installation.
In the below example you register to non alert notifications (badges and sounds only) :
Registering for remote notifications
- (void)applicationDidFinishLaunching:(UIApplication *)app {
// other setup tasks here....
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const void *devTokenBytes = [devToken bytes];
self.registered = YES;
[self sendProviderDeviceToken:devTokenBytes]; // custom method
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"Error in registration. Error: %#", err);
}
Hope this will help you.

Resources