Objective-C: How to Handle an iOS push notification properly? - ios

I have implemented everything correctly in my app to receive push notifications, i'm receiving the notifications just fine, but how can i do something when the user clicks on it?
Here's my code regarding the matter:
AppDelegate.m:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"Received notification: %#", userInfo);
NSLog(#"Hello from appDelegate");
}
It's working, i'm getting the userInfo and the other message in my Xcode log.
Now i want to do something (go to a specific segue) when the user clicks on the notification. I have seen the docs but it's very complicated and hard to follow.
I just need to know what function to use in the MainViewController.m
Any hints? thanks in advance.

You can post notifications (Using NSNotificationCenter) from AppDelegate on different events and then add observer in particular classes where ever you want to perform a particular operation.
Code Implementation
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSString *aStrEventType = userInfo[#"eventType"];
if ([aStrEventType isEqualToString:#"callWebService"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"callWebService" object:nil];
}else{
// Implement other notification here
}
}
Now in your particular class you can handle notification as follows.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:#"" selector:#selector(callMyWebService) name:nil object:nil];
}
-(void)callMyWebService{
//Perform your action.
}

Related

show a custome view when notification receive in active application

I need to show a universal custom view whenever i received a notification in a active app.
I have created a view , but i am not getting how to show that!
Can anyone help me out.
You have to handle the notification in the AppDelegate methods (usually application(_:​did​Receive​Remote​Notification:​fetch​Completion​Handler:​)) and launch the view in the form it can be shown in any screen of your app.
You can read the docs for UIApplicationDelegate here, section Responding to Notifications and Events.
You will be receiving the push notification in AppDelegate's application(_:​did​Receive​Remote​Notification:​fetch​Completion​Handler:​) from here you can handle.
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler
{
// 1. You can call your universal view from here
OR
// 2. You can post this local notification with information
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:myObject forKey:#"info"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"showNotification"
object:nil
userInfo:userInfo];
}
For 2nd Option, you will need add observer and receiving method:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveNotification:)
name:#"showNotification"
object:nil];
-(void)receiveNotification:(NSNotification *)notification {
// call your view
}

NSNotificationCenter and didReceiveRemoteNotification

I have some problems with NSNotificationCenter and didReceiveRemoteNotification. I want to open my ViewController when i receive new notification from APNS. Inside body notification i have objectId - it's key.
I try to open my ViewController into didReceiveRemoteNotification but it's not working ((
AppDelegate.m
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[[NSNotificationCenter defaultCenter]
postNotificationName:kDidReceiveRemoteNotification
object:userInfo];
}
NewsDetailViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(didReceiveRemoteNotification:)
name:kDidReceiveRemoteNotification
object:nil];
}
- (void)didReceiveRemoteNotification:(NSNotification *)notification
{
NSLog(#"%s %#",__func__,[notification.userInfo description]);
}
Const.h
#define kDidReceiveRemoteNotification #"UIApplicationDidReceiveRemoteNotification"
ViewController not loaded. i dont know what to do.
The current flow of the sample code you've attached is:
When receiving push notification, post a notification to NSNotificationCenter (something completely different and unrelated to push notifications).
When another view is loaded (someone needed to load this view before the push notification was received), subscribe to this NSNotificationCenter notification.
When the notification is posted, print it to log.
It was hard for me to understand this from your question, but if the view controller you're trying to launch as a result of receiving the push notification is NewsDetailViewController, then your code doesn't do that. What you're code does is prints out the notification to log (assuming that somebody else made sure that NewsDetailViewController is loaded before the push notification was received).
In order to load the NewsDetailViewController when the push notification is received, you don't need to post the notification to NSNotification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NewsDetailViewController *newsVC = [[NewsDetailViewController alloc] initWithNibName:#"NewsDetailViewController" bundle:nil];
[self.window.rootViewController.view addSubview:newsVC.view];
}
Or any other loading logic that works better for you. But in the current code you posted, there is no connection between receiving the push notification and loading the ViewController.
I hope this helps. Good luck!

Passing data received from a push notification from the AppDelegate to a ViewController

In my app, there's a collection view displaying a set of images retrieved from a web service. Each image has tags. So the app has the ability to filter images using tags as well.
Now I'm trying to add push notifications to this app. A push notification is sent when new images have been added to the server. These images are tagged say, latest. I'm passing that tag as the message via a push notification and what I need is when the user taps on the push notification to open the app, it should load the latest new images to the collection view.
I'm half way done. I receive the push notification with the message successfully to the didReceiveRemoteNotification method in the AppDelegate.m file. Now I need to pass it on to the view controller where the collection view is. I'm stuck at this point. I can't figure out how to send it over to the view controller.
I tried declaring a property in the App delegate, assign the message value to it and referring it from the view controller but it didn't work. I tied delegates, notification center, user defaults but nothing worked.
Can anyone please tell me how to accomplish this?
Thank you.
Edit:
Here's my code. The last method I tried was the local notifications.
AppDelegate.m
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"PushNotificationMessageReceivedNotification" object:nil userInfo:userInfo];
}
ViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(remoteNotificationReceived:) name:#"PushNotificationMessageReceivedNotification"
object:nil];
}
- (void)remoteNotificationReceived:(NSNotification *)notification
{
NSLog(#"Notification: %#", notification.userInfo);
NSString *msg = [[notification.userInfo valueForKey:#"aps"] valueForKey:#"alert"];
self.label.text = msg;
}
Case 1: if your app is background and user launches app with notification click then you have the check if app launched form notification or normal
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
NSDictionary *remoteNotificationPayload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotificationPayload) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"notification" object:nil userInfo:remoteNotificationPayload];
}
return YES; }
Case2: If your app is in forground notification will be received in didReceiveRemoteNotification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"userinfo %#",userInfo);
[[NSNotificationCenter defaultCenter] postNotificationName:#"notification" object:nil userInfo:userInfo];
}
Now you and add a observer in any controller with Local notification and do what you wand to do
I don't know it will work or not,its only my suggestion. I did't tried it before but in your case may be it work
user NSUserDefaults for this.
in your appDelegate.m
[[NSUserDefaults standardUserDefaults] setObject:imageArrayFromServer forKey:#"MyAppSpecificGloballyUniqueString"];
in your viewController.m
NSArray *myArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"MyAppSpecificGloballyUniqueString"];

Which Push Notification caused the app to resume from the background

My App receives APNS Push Notifications, and when a user receive more than one NSNotification, he should be able to open the app in a specific view according the NSNotification tapped.
So in the method
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler
I added this code to save all the notifications
if (self.notifications == nil) {
self.notifications = [[NSMutableArray alloc] init];
}
[notifications addObject:userInfo];
And every time the app becomes active again it does this
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started)
// while the application was inactive.
// If the application was previously in the background,
// optionally refresh the user interface.
[notifications removeAllObjects];
application.applicationIconBadgeNumber = 0;
}
Before removing all the objects and setting the badge to zero, I would like to handle which NSNotification made my app open from the background. And once I have which push NSNotification it was, I would like to pass all the data to a specific view.
Based on your comment about UILocalNotification usage
UILocalNotification has a userInfo property. When you create your local notification from the push notification, set the appropriate information into this property and then when the app delegate receives application:didReceiveLocalNotification: you can use that into to update your UI.
If you not use new iOS7 background fetch notifications.
In - (void)applicationDidBecomeActive:(UIApplication *)application before removing all object from notification array, check for notification
NSDictionary * myNotification = [notifications lastObject];
if (myNotification)
{
// is last notification
}
Is will work because app receive only notification that user tap on it
Send with your push notification, data, and use it when your app receives it.
In this example, i'm using the image file and alert, and sending it to all the views that are registered for this Notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
//Posting the notificaiton to the use, if its valid:
NSDictionary *returnDic = [userInfo objectForKey:#"aps"];
if (![returnDic objectForKey:#"alert"]) {
return;
}
NSString *alert = [NSString stringWithFormat:#"%#",[returnDic objectForKey:#"alert"]];
if (![returnDic objectForKey:#"MagnetID"]) {
return;
}
NSString *magnetImage = [returnDic objectForKey:#"MagnetImage"];
NSDictionary *dictionaryToSend = [NSDictionary dictionaryWithObjectsAndKeys:magnetImage,MAGNET_IMAGE,alert,MAGNET_ERROR_MESSEGE, nil];
//Posting to the rest of the views, the messege:
[[NSNotificationCenter defaultCenter] postNotificationName:USER_MESSEGE_RECEAVED object:nil userInfo:dictionaryToSend];
NSLog(#"Notifications - userInfo=%#",userInfo);
}
What you may do, is save the data that you need, by UserDefults or whatever you prefer, and at the "applicationDidBecomeActive" method, use that data to show the right view.
Hope this helps

iOS click on push notification open concrete viewcontroller

Is it possible to open concrete viewcontroller when user tap on push notification?
I have news app, main view controller have a lot of news, and when user tap on some new I open next viewcontroller with description of this news.
When user tap push notification, how I can open second view controller?
I tried to send Notification to my UINavigationController and push two controllers, but it doesn't work fine, it open only first viewcontroller.
you can handle your app, when you tap a local or push notification, implementing the application:didReceiveLocalNotification: or application: didReceiveRemoteNotification: method in your AppDelegate.m
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
}
If your app it's closed (not in background) you can verify if you received a notification in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary *userInfo = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
if ( userInfo != nil )
[self application:application didReceiveRemoteNotification:userInfo];
}
I don't know how you are handling your news but you can post a notification to your main view controller informing that you have receive a notification, passing the "id" or the info of your new and then create your second view controller (you will need to verify if your MainViewController is already created in the stack of your NavigationController):
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[NSNotificationCenter defaultCenter] postNotificationName:#"IHaveReceivedANotification" object:nil userInfo:userInfo];
}

Resources