Xcode Recieve notification only when app is active - objective-c

I write in Objective-C.
I'm using remote push up notification for app control. I don't want to disturb users with alerts and sounds when app is not active. What i need to do - if app is not active - do nothing when notification is recieved.
Thank you.

You want to send silent notifications. A notification sent without an aps key is silent. iOS will not play a sound, nor will it display a banner on the device. Your app will still receive such notifications, if it's running, and can respond as it chooses. If the app is in the background, it can display a local notification, or it can just ignore it.

Here are palyload structure which you need to receive for your case:
{
"aps" : {
"badge" : 5,
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}
BTWL: you can not mention badge as well, if you don't need it.

just add below code into your Appdelegate.m file
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
UIApplicationState state = [application applicationState];
if(state == UIApplicationStateActive)
{
//app in active mode
// add your code as you want to handle
}
else{
// app is in terminated mode
}
}

It was easier than i thought. Just no alert and sound elements in array in section aps.
No alert - nothing to show.
No sound - nothing to play.

Related

Flutter: FirebaseMessaging.onBackgroundMessage never execute in iOS

I want to execute some code in onBackgroundMessage when app is in background or killed.
I am getting push notifications as aspected but onBackgroundMessage function is never executed in iOS. It works perfectly in Android devices.
Here is my code:
Future<void> _backgroundHandler(RemoteMessage message) async{
await Firebase.initializeApp();
dynamic isCall = message.data['status'];
print(isCall);
if(isCall == 'call'){
//.....
}else{
NotificationHandler.flutterLocalNotificationPlugin.cancelAll();
}
FirebaseNotifications.showNotification(message.data);
}
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_backgroundHandler);
runApp(const MyApp());
}
I also add APNs and add capabilities Background Modes and Push Notifications. Tested on real device.
What should have to do to execute FirebaseMessaging.onBackgroundMessage function in iOS?
You need to set content-available to true in your notification payload from backend.
This value let OS know that some data is available with the notification and allow that callback to be executed even when your app is in terminated state.
Client
for ios:
foreground - onMessage;
background - onBackgroundMessage;
terminated - onBackgroundMessage.
BUT
if app was terminated, first notification will be handled with getInitialMessage, because first notification wakes up the app
Server
exapmle of config:
messaging.Message(
token=recipient['fcm_token'], data={**message_data, 'user_id': str(recipient['user_id'])},
notification=messaging.Notification(
title=message_data['title'], body=message_data['body'], image=message_data['image'],
),
fcm_options=messaging.FCMOptions(analytics_label=message_data.get('analytics_label', None)),
apns=messaging.APNSConfig(
payload=messaging.APNSPayload(
aps=messaging.Aps(
content_available=True,
),
),
headers={'apns-priority': '5'},
),
)
need content_available=True and maybe headers={'apns-priority': '5'}

Clear Previous Expo Push Notifications

I have my app in Expo pushing a notification when somebody sends a message, but if that person sends multiple messages a second notification is pushed.
Is there anything I can do to clear the previous notification, or simply update the notification instead of adding a second notification to the list?
Basically I need to force an override or dismiss previous notifications.
The approach I was hoping to use was to add a listener which cleared notifications before appending, but it seems that this only works when the app is in the foreground.
Is there a recommended approach to this currently?
You can clear any or all previous notifications in expo-notifications. Your question is not clear but I am guessing you want to clear all previous notification if new notification is received. You have to spot the best place when to clear notifications on your code. But here are some tips (use the following code in the useEffect hook) -
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
// DISMISS ALL NOTIFICATION AFTER INTERACTION
Notifications.dismissAllNotificationsAsync();
});
If you want to dismiss specific notification in that case, use dismissNotificationAsync(identifier: string): Promise method.
Just in case, if you want to dismiss all notifications when receiving a new one while the app is foregrounded (use the following code in the useEffect hook).
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
// setNotification(notification);
// DISMISS ALL NOTIFICATION UPON RECEIVING NOTIFICATION WHILE IN FOREGROUND
Notifications.dismissAllNotificationsAsync();
});
You can use Notifications.dismissAllNotificationsAsync() method or dismissNotificationAsync(identifier: string): Promise method anywhere you like but you need to spot where to best use them.
_handleNotification = (notification) => {
this.setState({notification: notification});
console.log('get notification', this.state.notification);
let localnotificationId = this.state.notification.notificationId;
setTimeout(function () {
Notifications.dismissNotificationAsync(localnotificationId);
}, 10000)
};
This is how I do in NodeJS

How to make application NOT redirect me when app is running and push notification comes and I am NOT tapping on it

I have an application and PUSHs work fine when the app is on background I tap on push notification and it redirects me - OK.
But here is the situation which i have to fix:
1 step: I open the app, working with it, it is active
2 step: notification comes but user is not seeing anything AND he gets redirected to another ViewController(according to push notification info) UNEXPECTEDLY.
I need the app NOT to redirect anywhere when it is active unless the push notification is actually tapped.
I found a solution!
in didReceiveRemoteNotification method add if statement:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if application.applicationState == .inactive || application.applicationState == .background {
//here add you actions
}
}

WatchConnectivity Framework : WKSession is maintain the queue which I requested To Watch

I have create an application which is sending data to watch for showing.
When the watch is screen is active then it sending data perfectly, but when watch sleeps then an error occurred that device is not active.
My question is that when the watch is active any how it will get that data which send via using WKSession sendMessage method from my iPhone?
If the watch screen is off, the calling sendMessage on the iPhone won't work. You can only send data in real time when the watch screen is on. This is different than when you are using sendMessage from the watch to the iPhone (iPhone screen can be off). This is the block of code I use anytime I call sendMessage from my iPhone code:
// Send messages to any paired apple watch.
func tryWatchSendMessage(message: [String : AnyObject]) {
if self.session != nil && self.session.paired && self.session.watchAppInstalled {
self.session.sendMessage(message, replyHandler: nil) { (error) -> Void in
// If the message failed to send, queue it up for future transfer
self.session.transferUserInfo(message)
}
}
}
Then I setup the apple watch app to have the same handler if it gets the data via sendMessage or transferUserInfo.

How handle silent notifications in iOS

I need to fetch data from parse SDK and update in core data after receiving push notification(silent notification)in foreground and background.how to receive silent push notification and update data(without on click of notification).Here my code is
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
/*
//notification data format from server
{ "operation": "Update",
“Element”: “1234”,
"action": "db" }
//after receiving update notification ,i should fetch that unique element(1234) data from parse and save data into database.
*/
if ([[userInfo objectForKey:#"operation"] isEqualToString:#"Update"])
{
NSLog(#"update notication called");
//fetching data and updating database using updateDatabase method ,its implemented in some other class.
[database updateDatabase:[userInfo objectForKey:#“Element”]];
}
}
this is silent notification, So how to handle silent notification in iOS. thanks
you have to enable the background mode for that. Click on your Project Name in the file inspector, then select your target and select the tab "Capabilities". Now turn "Background Modes" on and select "Push Notifications".
Modify your payload and make sure you've content-available set to '1'. This tag is required for silent notification. Without this the payload will be a non-silent notification.
{
aps: {
content-available: 1,
sound: "default"
}
}