iPhone client not registering for push? - iphone

I "think" my app is not registering for push notifications.
It should be as simple as adding the code to didFinishLaunchingWithOptions and then the when tested the app alert for push notifications should (but does not in my case) pop up.
my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
return YES;
}
This is an iPad app. It is running without push on my real device so I assume the provisioning is correct.
Any ideas? I do not get the push Don't allow/ok pop up.

Do u have this code in your delegate?
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString
stringWithFormat:#"Device Token=%#",deviceToken];
NSLog(str);
}
You should get the device token generated and put it in your server where you want to push your notification..
If let say you have everything right on the iphone part, the problem may lies on your server code where you push your notification..
Take a look at this tutorial about push notification :
http://mobiforge.com/developing/story/programming-apple-push-notification-services

You need to implement the delegate methods and set up the certificates on your server. Here is some code for the objc side:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
NSString *token = [[devToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"token"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:#""] forKey:#"token"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:[[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleDisplayName"]
message:[[userInfo objectForKey:#"aps"] objectForKey:#"alert"]
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[alert show];
}
A good tutorial about setting up the server and Dev Center certs - How to renew your Apple Push Notification Push SSL Certificate
How to build an Apple Push Notification provider server (tutorial)

Yes I have the other part of the code also. I was under the impression that the pop up would happen weather the server stuff was done yet or not?
I got it working. I had to get a new provisioning file. Delete the old one. The go into the app folder. View contents of the project file. Open with text editor the file with the provisioning key in it and swap the key (two spots) out with the new key code.
Now it works. Thanks for the help.

Related

iOS: Push Notification and Re-Registering the device at Login.

I need to register the device for Push Notification each time the User Logs In.
Right now in my AppDelete.m I have the following code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [[token componentsSeparatedByString:#" "] componentsJoinedByString:#""];
[self.pushClient registerDeviceToken:token withUser:loggedInUserName onSuccess:^{
NSLog(#"successful registration");
} onFailure:^(NSError *error) {
NSLog(#"error: %#", [error userInfo]);
}];
}
Q. What do I need to do to call the above methods in my App Delegate each time the User Logs In? i.e. The app is running. A User logs out and logs back in with a different username, and now I need to register the device with that user name, what should I do?
You can always call the method registerForRemoteNotificationTypes after user is logged in.
You need to persist APNS token, thats the way going forward for your situation.
As and when your app comes to foreground, you will get call in registerForRemoteNotificationTypes. Now
remove old APNS token from NSUserDefaults if any (or whatever you like for persistence)
save APNS token into NSUserDefaults
and use saved token.

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.

application:didRegisterForRemoteNotificationsWithDeviceToken: never called

I'm developing an iOS app with Urban Airship push notifications
I've seen that after these logs:
"Updating device token
Skipping device token update: no token, already up to date, or user is being updated."
Must come this log:
"Device token registered on Urban Airship successfully."
I don't receive the latter.
This function is never called:
application:didRegisterForRemoteNotificationsWithDeviceToken:
What am I doing wrong?
Thank you,
Nur
=====EDIT======
I followed the UrbanAirship tutorial here
Here's the code I'm using:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSMutableDictionary *takeOffOptions = [[[NSMutableDictionary alloc] init] autorelease];
[takeOffOptions setValue:launchOptions forKey:UAirshipTakeOffOptionsLaunchOptionsKey];
[UAirship takeOff:takeOffOptions];
[[UAPush shared] updateAlias:#"some_alias"];
[[UIApplication sharedApplication]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[[UAirship shared] registerDeviceToken:deviceToken];
}

Get device token to push notify the second time on iPhone

I need to obtain the device token on my iPhone to test the push notify.
On my iPhone I had already agreed to notify push permissions. I try to remove and reinstall the app but nothing. I try to put a breackpoint in the didRegisterForRemoteNotificationsWithDeviceToken method but nothing.
Any suggestion?
This is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/**** PUSH NOTIFY ****/
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSMutableString *str = [[NSMutableString alloc] initWithFormat:#"http://www.mysite.com/storeToken.php?task=register&token=%#", [self stringWithDeviceToken:deviceToken]];
//NSLog(#"%#",str);
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
[pref setObject:[self stringWithDeviceToken:deviceToken] forKey:#"token"];
[pref synchronize];
NSURL *url = [NSURL URLWithString:str];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
[str release];
}
- (NSString*)stringWithDeviceToken:(NSData*)deviceToken {
const char* data = [deviceToken bytes];
NSMutableString* token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
return [[token copy] autorelease];
}
This is the error that it print:
Error: Error Domain=NSCocoaErrorDomain Code=3000 "nessuna stringa di autorizzazione 'aps-environment' valida trovata per l'applicazione" UserInfo=0x296e80 {NSLocalizedDescription=nessuna stringa di autorizzazione 'aps-environment' valida trovata per l'applicazione}
It is good to have another delegate method for error handling:
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Fail to register for remote notifications: %#", [error localizedDescription]);
}
After question update it's more clear that problem is in wrong provisioning profile (generic or without 'aps-evironment'). So:
Remove all expired profiles and all profiles for that app from both XCode and device
Check push notifications are enabled for your app (in provisioning portal)
Download provisioning profile from portal, install it to XCode
Check that selected profile (in build settings / codesigning identity) matches the app, and is not the generic/wildcard one (sometimes autoselection goes wrong)
As usual (XCode caching "magic"), it's better to restart XCode and remove the application from device before build
Build & Pray

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;
}
}