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.
Related
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.
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
I'm making an applikation which is using push notifications, I am currently using pushbots for the push notifications. I was wondering if there is any way to intercept the notifications that is received by the application and check the notification before the notification is shown on the device. And if the data in the notification is not correct, dont show a notification at all? Is this possible with pushbot or do I need to do it all by my self?
Yes, you can achieve this behaviour playing around with Local Notifications.
You can configure your payload without an alert and "content-available": "1" so your application can receive notifications without showing them to the user.
// Payload
{
aps: {
"content-available": 1
},
text: 'my alert message' // your custom info
}
And in your app code, register notifications as
// Register notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeNewsstandContentAvailability];
Then, the key is to trigger Local Notifications in the application:didReceiveRemoteNotification:fetchCompletionHandler: method based on some condition
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(#"push data package: %#", userInfo);
// Retrieve your data
NSString *text = [userInfo objectForKey:#"text"];
BOOL mustShow = YES;
// Only show notification if app is background and your custom condition
if ((state == UIApplicationStateInactive || state == UIApplicationStateBackground)
&& mustShow) {
// Raise the local notification a second after received
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
localNotification.alertBody = text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
This way you can "intercept" the notifications before "displaying" them to the user.
You can't prevent the notification from being shown once it reaches the device (assuming it contains an alert field in the aps dictionary - if it doesn't, no notification will be shown anyway).
You should determine in your server which notifications should be sent to which device tokens. You can associate device tokens with users in your DB, if your functionality requires it.
Even if what you request was possible, it would be very inefficient to send notifications to all the devices that installed your app, and then only display the notification in a small subset of them.
Hi Im currently developing an app where i have push notifications activated. I use parse.com. I have got it working so far that i can send a notification and the device receives it and i also get a badge on the app. But when i open the nothing happens and the badge does not disappear. I've set it in my appdelegate.m so parse is handling the push notifications. Heres some code that im using:
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken {
// Store the deviceToken in the current installation and save it to Parse.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation setDeviceTokenFromData:newDeviceToken];
[currentInstallation saveInBackground];
}
and also:
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
[PFPush handlePush:userInfo];
}
Thanks
Ok thaks but how to i show the content of the push notification in the alert view? Or is that not a problem do i just have to configure a alertview with no text?
There are two scenarios:
App closed
When the app is closed and the user taps on a notification it's like when taps on the app icon. The app starts from application:didFinishLaunchingWithOptions:. To know if the app is opened normal (tap icon) or with a notification, just check the dictionary launchOptions for the key UIApplicationLaunchOptionsRemoteNotificationKey.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary * pushDictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (pushDictionary)
{
//AlertView
}
}
App opened
When the app is opened there are two possible case
App in background UIApplicationStateInactive
App in foreground UIApplicationStateActive
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if (application.applicationState == UIApplicationStateInactive)
{
//AlertView
}
else if (application.applicationState == UIApplicationStateActive)
{
// AlertView
}
}
pushDictionary and userInfo are exactly the same dictionary that represents the notification.
Edit 1
A push notification is a JSON file that iOS automatically convert into a NSDictionary. The standard configuration is:
{"aps":
{
"alert":"Text message",
"sound":"default",
"badge":"1" //the number shown on the app's icon
}
}
From this base you can extend the JSON and put inside your own content. For example
{"aps":
{
"alert":"Text message",
"sound":"default",
"badge":"1" //the number shown on the app's icon
},
"Name":"Fry"
}
Now you can retrive the name in this very simple way:
NSString * name = userInfo[#"Name"];
and show it in the alert.
Edit 2
To show the content of push in UIAlertView just do this:
UIAlertView *av = [[UIAlertView alloc] initWithTitle:name
message:name
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[av show];
If you receive push notification while your app isn't active (killed)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
will not be triggered. Instead of that you will have to use object with key UIApplicationLaunchOptionsRemoteNotificationKey from launchOptions dictionary inside
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
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{
}