IOS, Local notification in app - not work - ios

I make some checks and then fire it, but its work only when the app is in the background.
How can I fire notification when the user is in the app?
I am using the didReceiveRemoteNotification method but its response only in the background and not in the app. I also tried to fire a notification in
the viewDidLoad method but it didn't work either.
- (void) application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
UILocalNotification* n1 = [[UILocalNotification alloc] init];
n1.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
n1.alertBody = #“test”;
n1.soundName = #"default";
[[UIApplication sharedApplication] scheduleLocalNotification: n1];
completionHandler(UIBackgroundFetchResultNewData);
}

UILocalNotification are designed to be fired when user is not using the application as per UILocalNotification say here in the apple documentation
if you want to know if the application has received an UILocalNotification you may use following code.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if ([notification.alertBody isEqualToString:#"Application is timeout!"])
{
// show an alert regarding your notification
}
}

Related

Notification not triggered when app in foreground - iOS

I'm using firebase to implement push notifications in iOS, with objective c.
I have the method application:didReceiveRemoteNotification:fetchCompletionHandler, which should be triggered when the app is in background and the user taps the notification and also when the app is in foreground, according to its description. Thing is it only works in background (or when the app is no running).
Am I forgetting something?
Thanks for the help.
You can use this below code:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive)
{
//app is in foreground
//the push is in your control
UILocalNotification *localNotification =
[[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName =
UILocalNotificationDefaultSoundName;
localNotification.alertBody = message;
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication]
scheduleLocalNotification:localNotification];
}
else
{
//app is in background:
//iOS is responsible for displaying push alerts, banner etc..
}
}
For iOS 10 and above below method is called when application is in foreground:
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
So you need to observe this method to handle notification while app is in foreground
The standart example for iOS Firebase Notifications is implemented in AppDelegate like completionHandler(UIBackgroundFetchResultNewData);
If you like in foreground you have to implemt it.

Send silent push notification to app, update location and send to server in background

I want to send a silent push notification to an application that is in background, then fetch the current user location and send it to a web service.
I implemented push notification methods and also those two:
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSDate *fetchStart = [NSDate date];
[self sendLocationToServerWithCompletionHandler:^(UIBackgroundFetchResult result) {
completionHandler(result);
NSDate *fetchEnd = [NSDate date];
NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart];
NSLog(#"Background Fetch Duration: %f seconds", timeElapsed);
}];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
}
I've also created a method that will send the location to the server:
- (void)sendLocationToServerWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSDictionary *params = #{
#"UserId" : self.userId,
#"Latitude" : self.latitude,
#"Longitude" : self.longitude
}
ServerManager *manager = [ServerManager sharedManager];
[manager sendLocationToServerWithCompletion:^(BOOL success) {
if (success)
{
completionHandler(UIBackgroundFetchResultNewData);
}
else
{
completionHandler(UIBackgroundFetchResultFailed);
}
}];
}
I just can't understand how they all work together, will Apple approve that, is it even possible and where does the location background fetch goes into.
Thanks in advance.
Here's a brief sketch of what you can do to give you an idea. Its assuming there is a model class implemented as a singleton and there's some pseudo code.
// App delegate
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
completionHandler(UIBackgroundFetchResultNewData);
[[YourModel singleton] pushNotificationReceived: userInfo];
}
// Model
- (void) pushNotificationReceived:(NSDictionary *) userInfo
{
[self registerBackgroundTaskHandler];
get the location here, or start getting the location
[self sendLocationToServerWithCompletionHandler: your completion handler];
}
- (void) registerBackgroundTaskHandler
{
__block UIApplication *app = [UIApplication sharedApplication];
self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
DDLogInfo(#"BACKGROUND Background task expiration handler called");
[app endBackgroundTask:self.backgroundTaskId];
self.backgroundTaskId = 0;
}];
}
- (void) endBackgroundTask
{
if (self.backgroundTaskId)
{
UIApplication *app = [UIApplication sharedApplication];
[app endBackgroundTask:self.backgroundTaskId];
self.backgroundTaskId = 0;
}
}
You'll need to get the location before you can send it. If you are just getting one location and you're using iOS9 you can use CLLocationManager:requestLocation: and you could fit this in relatively easily into where I've said "get the location here".
If you're not using iOS 9 (requestLocation is new with iOS 9) its a bit more complex.
How to use the location manager is a topic in itself and too much code to post here. You need to read and study all about using the location manger before you can incorporate it.
If you need a stream of location updates it gets more complex and where it says "or start getting the location" is a lot more involved then is implied in the pseudo code.
My recommendation, start with iOS9 and getting one instance of the location, then when thats working, add more functionality or iOS8 support if you need it.

Local Notification Banner and sound not working in Foreground Objective-C

Im trying to implement the local notification to my app and I implemented the local notification but the problem is .... I'm not getting the Notification BANNER and SOUND when my app is in the foreground. But it is working good when my app is in background.
How to bring the notification banner and sound in foreground.. Is that possible?
this is my piece of code...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Handle launching from a notification
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (locationNotification) {
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
if (application.applicationState == UIApplicationStateActive ) {
NSLog(#"it entered active push");
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = userInfo[#"aps"][#"alert"][#"body"];
localNotification.alertLaunchImage= userInfo[#"acme1"];
localNotification.fireDate = [NSDate date];
localNotification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Remove the badge number
application.applicationIconBadgeNumber = 0;
}
-(void)application:(UIApplication*)application didReceiveLocalNotification:(UILocalNotification *)notification{
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:notification.alertBody
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
If the app is active you will be notified by application:didReceiveLocalNotification: in app delegate only. There you can display custom banner like view on the top viewcontroller presented on the view hierarchy . Just look at the whatsapp notification when the app is open
If the application is active then you will not recieve any sound, badge or alert, however the application delegate application:didReceiveLocalNotification: will be called
From apple docs
If the application is foremost and visible when the system delivers the notification, no alert is shown, no icon is badged, and no sound is played. However, the application:didReceiveLocalNotification: is called if the application delegate implements it. The UILocalNotification instance is passed into this method, and the delegate can check its properties or access any custom data from the userInfo dictionary.
If your app is currently running and active (i.e. visible), you will not see the alert message. Instead iOS will deliver the notification to your app directly through the following method
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
No it will not play a sound or show a banner. However in your apps delegate , did receive notification will still be called where you can then show an alert view if you wish to notify a user.
You can however add audio manually.
- (void) application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
SystemSoundID systemSoundID;
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:#"blip"
withExtension:#"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &systemSoundID);
AudioServicesPlaySystemSound(systemSoundID);
}
Local notification in Foreground

Receiving APNS notification but cant display on device in ios

Hello everyone,
I am trying how to implement pushnotification.For this i have read apple official document for push notification and also read raywenderlich blog and i understand the flow of pushnotication very well. I have created development and production certificate,profile and its working fine and push was successfully sent and receiving in -
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
*** display message in uialertview******
}
but my problem is how can i display push in my device like other push notification on top up side for both when my application is foreground and background too.
currently i am trying for IOS 7.0 and XCode Version 5.1.1 (5B1008)
Thanks In advance.
First of all check via these methods in App Delegate that if your registered successfully to APNS.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
}
then in
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSDictionary *Notification = userInfo;
NSString *title = [(NSDictionary*)[(NSDictionary*)[Notification valueForKey:#"aps"] valueForKey:#"alert"] valueForKey:#"title"];
NSString *body = [(NSDictionary*)[(NSDictionary*)[Notification valueForKey:#"aps"] valueForKey:#"alert"] valueForKey:#"body"];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
}
else if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateInactive || [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = body;
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
If your application is in active state show UIAlertView. if its not you need to show a UILocalNotification.
When you are in Background mode then push notification will display as per your application notification settings from notification centre. you dont have to display ios will do that.
when you are in Foreground mode then notification will receive and -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo method will be called. so using this method you get userinfo. just NSLog userinfo dictionary and then you can create customview with label at top and animate it like ios default banner.
Hope this will help you.
As per Apple's note push/local notification will be display only when app is background mode. If notification is arrive at the time of app is on foreground/active then you need to manually manage it because iOS won't show a notification banner/alert That's default design.
I just put my logic here for manage notification when app in foreground mode:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
// check the application state for app is active or not.
if (application.applicationState == UIApplicationStateActive)
{
// Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Receive a Remote Notification" message:[NSString stringWithFormat:#"Your App name received this notification while it was running:\n%#",[[userInfo objectForKey:#"aps"] objectForKey:#"alert"]]delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}
If you want to receive notification in top of the device like banner style then follow these steps.
First, you need to launch the 'Settings' app on your iOS device.
Once you're in, choose 'Notifications' from the list of options.
Here's a list of every app that supports push notifications. The ones at the top have been granted permission by you
You can also set the alert style. You can choose the banners that conveniently appear at the top of the screen, or full-on pop-ups that force you to take action before they go away. Or you can just choose 'None'.
For more detail check this link.
Hope you will get something from my answer.

UINotification ios not received when app is in background

I am using notification in one of my app ,when app is active , notification is received , i process data and everything is fine , but I do not receive any notification when app is in background or killed.What is the issue can any one plz help me ?
Thank you!
Here is what I doing so far
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
tokenstring = [[NSString alloc] initWithFormat:#"%#",deviceToken];
tokenstring = [tokenstring stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
tokenstring = [[NSString alloc]initWithFormat:#"%#",[tokenstring stringByReplacingOccurrencesOfString:#" " withString:#""]];
NSLog(#"TokeinID:>> %#",tokenstring);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"didReceiveRemoteNotification: %#",userInfo);
AudioServicesPlaySystemSound(1002);
//Some code or logic
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(#"didFailToRegisterForRemoteNotificationsWithError: %#",err.description);
}
When you receive remote notifications, -application:didReceiveRemoteNotification: is only called when your app is in the foreground. If your app is in the background or terminated, then the OS may display an alert or play a sound (depending on the aps dictionary in the notification), but the delegate method is not called.
The remote notification received in the background will only passed to your application if it is launched with that notification's action button, and then you need to look at the launch options dictionary on -application:didFinishLaunchingWithOptions: to see the content of the notification.
If you're looking at new content fetching/remote notification background support with iOS7, check Will iOS launch my app into the background if it was force-quit by the user? and see if that helps, as there are very specific circumstances that those functions work in.
little code ..
When app is not running
(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
is called ..
where u need to check for push notification
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (notification) {
NSLog(#"app recieved notification from remote%#",notification);
[self application:application didReceiveRemoteNotification:(NSDictionary*)notification];
}else{
}

Resources