how to handle push payload when the app closed? - iphone

i am sending push payload to my users with the follow content :
{"aps": {"alert": "Go To Google", "sound": "Default","url":"http://www.google.com"}}
everything goes well when the pp is running but in the background.
if i am receiving the push and the app is closed i am open it and nothing happen.
i am trying to redirect to this url in the payload.
again when the app is running from the background it goes well.
this is the implementation so far AppDelegate.m:
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
RedirectedUri = [[userInfo objectForKey:#"aps"] objectForKey:#"url"];
NSLog(#"%#",RedirectedUri);
[self Redirect:RedirectedUri];
}
need some help please.

Additionally, add the following to your code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self applicationDidFinishLaunching:application];
if (launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
RedirectedUri = [[dictionary objectForKey:#"aps"] objectForKey:#"url"];
[self Redirect:RedirectedUri];
}
}
return YES;
}

Related

AppleWatch : On button tap from the the AppleWach Open URL on iPhone device

I want to open url from the AppleWatch app button tap to the mobile application.
Please any one have any idea regarding to these?
Added this in your AppDelegate.m
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.google.com"]];
}
This is what you have to apply on button tap in Watch App
NSURL *url = // your URL
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:url, #"URLKey", nil];
[WKInterfaceController openParentApplication:dic reply:^(NSDictionary *replyInfo, NSError *error)
{
NSLog(#"%# %#",replyInfo, error);
}];
And you can receive this request in iPhone in AppDelegate.m
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply
{
//receive userinfo dictionary here to perform specific request from watch
NSString *url = [userInfo objectForKey:#"URLKey"];
// perform operation on url
reply(#{#"Notification Alert":[NSString stringWithFormat:#"%f",dist]});
}

AppDelegate is not listening to APNS Push Notification

When my app enters background, AppDelegate is not listening to the new push notification from APNS. But strange thing is that it doesn't happen all the time. Sometimes it works, sometimes it does not. I can't figure out why.
Here is my sample code for listening APNS Notification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert)];
}
if (launchOptions != nil)
{
NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
}
}
return YES;
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
NSLog(#"Received notification: %#", userInfo);
[self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:nil];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(#"Received notification background: %#", userInfo);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC),
dispatch_get_main_queue(), ^{
// Check result of your operation and call completion block with the result
completionHandler(UIBackgroundFetchResultNewData);
});
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[application registerForRemoteNotifications];
}
In background/closed mode,no code will execute and none of the delegate method will be invoked.This time push notification is handled by OS itself.The app badge is set by push notification payload value coming from server side.
If you are not getting app badge in background,it is a badge number issue from server side.Check whether the push notification payload contains application badge field and set to values greater than 0.
This link have same issue and resolved it.
Try to change your line..
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound categories:nil]];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];
}
in iOS 8 you have to use "UIUserNotificationTypeBadge"...
Hope this will work for you..

App with playerduel functionality doesn't get push notification

I am developing application which support playerduel framework. In which two players can play with each other. Person can send challenge to another one.
i follow the documentation following. https://docs.urbanairship.com/display/DOCS/Getting+Started%3A+iOS%3A+Push
I can get notification when i send it from command line (for testing) as describe in above documentation. But when i play game. Playerdual can't send notification when some one send challenge to another.
appdelegate code :-
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//Init Airship launch options
NSMutableDictionary *takeOffOptions = [[[NSMutableDictionary alloc] init] autorelease];
[takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];
// Create Airship singleton that's used to talk to Urban Airship servers.
// Please populate AirshipConfig.plist with your info from http://go.urbanairship.com
[UAirship takeOff:takeOffOptions];
// Register for notifications
[[UAPush shared]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)];
// Override point for customization after application launch.
self.appStarted = YES;
UIImage *bgImage= [UIImage imageNamed:#"default.png"];
[PlayerDuel initializeWithGameKey:#"gamekey" andBackground:bgImage
andDelegate:[navigationController.viewControllers objectAtIndex:0] andOrientation:UIInterfaceOrientationPortrait];
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"deviceToken:- %#",deviceToken);
// Updates the device token and registers the token with UA
[[UAPush shared] registerDeviceToken:deviceToken];
[PlayerDuel registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
for (id key in userInfo) {
NSLog(#"key: %#, value: %#", key, [userInfo objectForKey:key]);
}
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
NSString *itemName = #"my app";
NSString *messageTitle = [apsInfo objectForKey:#"alert"];
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive){
AudioServicesPlaySystemSound(1007);
[self _showAlert:messageTitle withTitle:itemName];
}
else{
UIViewController *viewController = navigationController.visibleViewController;
// NSLog(#"Controller Name:- %#",viewController);
[viewController.view reloadInputViews];
[viewController playerDuelStartGame:nil];
}
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
}
If the push notifications work directly through Urban Airship and not through PlayerDuel, You probably didn't specify the right urban airship details in PlayerDuel's developers website. Make sure you put Urban Airship's Master Secret and not the App Secret in PlayerDuel's website.
I have used App Secrete as Urban Airship Key: . This is wrong. When i change it value as App Key . It works fine.

How to manage notification when users click on badge

I have a question to ask about notifications. After some hours to learn how to implement push notifications on iPhone, it now arrives!
How do I manage users that click on badge or click view on alert? What happen when users click there?
I tried to send me some notification and the number on the icon of application in springboard increments. In which way clicking there it's possible to show a uiview to manage the notification arrived and show the message read and unread?
Is there a tutorial for it? I want to save all the messages inside a uitableview.
You want to read Handling Local and Remote Notifications
Basically in your application delegate, you want to implement:
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
and
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
And process the launchOptions / userInfo for the notification data.
How I normally process the data is:
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary* userInfo =
[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo) {
[self processRemoteNotification:userInfo];
}
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[self processRemoteNotification:userInfo];
}
The format for userInfo is documented the The Notification Payload section.
e.g. the "aps" key will give you another NSDictionary, then looking up the "alert" key will give you the alert message that was displayed. Also, any custom data you send in the JSON payload will be in there as well.
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alertMsg = #"";
NSString *badge = #"";
NSString *sound = #"";
NSString *custom = #"";
if( [apsInfo objectForKey:#"alert"] != NULL)
{
alertMsg = [apsInfo objectForKey:#"alert"];
}
if( [apsInfo objectForKey:#"badge"] != NULL)
{
badge = [apsInfo objectForKey:#"badge"];
}
if( [apsInfo objectForKey:#"sound"] != NULL)
{
sound = [apsInfo objectForKey:#"sound"];
}
if( [userInfo objectForKey:#"Custom"] != NULL)
{
custom = [userInfo objectForKey:#"Custom"];
}

Is it me or xcode... Somethings wrong with my braces and it just causes errors! Please help! iPhone SDK + Urban Push

Help!
I cant find whats wrong. My code is up and mostly running and i needed to incorporate Urban Air push notification and there is something wrong with my code. If there is a better or different way to incorporate this that works without my errors I would appreciate that.
I took this code from a tut of Urban Airmail. I wasnt sure what to inlude and what not to from the sample app.
Now for my code. Ill notate where I get errors They are stray / errors and expected ; b4 :
errors
If you could fix the code that would be awesome!
//
// SuperSlickAppDelegate.m
// SuperSlick
//
// Created by on 8/2/10.
// Copyright __MyCompanyName__ 2010. All rights reserved.
//
#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>
#import "SuperSlickAppDelegate.h"
#import "SuperSlickViewController.h"
#import "Reachability.h"
#implementation SuperSlickAppDelegate
#synthesize window;
#synthesize viewController;
#pragma mark -
#pragma mark Application lifecycle
#define kApplicationKey #"rnftzaemRp2HJMsNjwZvGQ"
#define kApplicationSecret #"X1XdTjdWQIaL72e-gXew5A"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
Reachability *r = [Reachability reachabilityWithHostName:#"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"You require an internet connection via WiFi or cellular network to use this! Try the settings app for WiFi Connectivity." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
//Register for notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];
//ERROR HERE in line above Stray 357
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
//ERROR HERE Wrong type argument to unary minus + stray
// Get a hex string from the device token with no spaces or < >
self.deviceToken = [[[[_deviceToken description] stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"Device Token: %#", self.deviceToken);
if ([application enabledRemoteNotificationTypes] == 0) {
NSLog(#"Notifications are disabled for this application. Not registering with Urban Airship");
return;
}
// this is straight out of the UA sample code
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
NSString *UAServer = #"https://go.urbanairship.com";
NSString *urlString = [NSString stringWithFormat:#"%#%#%#/", UAServer, #"/api/device_tokens/", self.deviceToken];
NSURL *url = [NSURL URLWithString: urlString];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
request.requestMethod = #"PUT";
// Authenticate to the server
request.username = kApplicationKey;
request.password = kApplicationSecret;
[request setDelegate:self];
[request setDidFinishSelector: #selector(registrationSuccessMethod:)]; // if you want to do something with the token
[request setDidFailSelector: #selector(requestWentWrong:)];
[queue addOperation:request];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
NSLog(#"Failed to register with error: %#", error);
}
- (void)requestWentWrong: (ASIHTTPRequest *)request {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSError *_error = [request error];
NSLog(#"ERROR: NSError query result: %#", _error);
UIAlertView *someError = [[UIAlertView alloc] initWithTitle:
#"Network error" message: NSLocalizedString( #"Error registering with notifiction server",
#"Error registering with notifiction server")
delegate: self
cancelButtonTitle: #"OK"
otherButtonTitles: nil];
[someError show];
[someError release];
}
// Add the view controller's view to the window and display.
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
}
- (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.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
New Code that has troubles:
//Register for notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];
;}}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
//ERROR HERE Wrong type argument to unary minus and semi colon b4
Doesn't look like you ever ended your application:didFinishLaunchingWithOptions: method - you should have an end brace after this line:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes...
So it should look like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];
//ERROR HERE in line above Stray 357
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
...
}
That should do it.
For your second code block - without seeing the surrounding code it's difficult to see what you're trying to do...you likely shouldn't have:
;}}
It should probably just be:
}
If you are looking for unbalanced parentheses, then this is probably the part that is giving you troubles:
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
}