How to Get Device Token in didFinishLaunchingWithOptions - iphone

I am calling device token in my first viewcontroller. And I cant get result because Device token is null. Here below is my code in appdelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"Device Token ---%#", token);
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
When I am calling in Viewcontroller :
NSString *token= [[NSUserDefaults standardUserDefaults] objectForKey:#"DeviceToken"];
token is null.

NSString *device = [deviceToken description];
device = [device stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
device = [device stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"My device is: %#", device);
This worked perfectly for me in my device.

Refer to Kulss' answer in this SO Answer:
How can I convert my device token (NSData) into an NSString?
You should be parsing the bytes not the description.

First
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Add this in Application.h

try this one my friend....
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
#if !TARGET_IPHONE_SIMULATOR
// Prepare the Device Token for Registration (remove spaces and < >)
token = [[[[devToken description]
stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"%#",token);
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
#endif
}
/**
* Failed to Register for Remote Notifications
*/
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if !TARGET_IPHONE_SIMULATOR
NSLog(#"Error in registration. Error: %#", error);
#endif
}
Happy Coding!!!!

Add two methods didRegister and didFailToRegister, and confirm are u getting a call in didRegister or in didFailedToRegister.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(#"Device Token=> %#",deviceToken);
//Parse your device toke
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Error in registration. Error: %#", error.description);
}
and assure are u getting succesfully ur device token. Or u r failed to registerForRemote...

You can try this one
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*) deviceToken {
NSString *pushToken = [deviceToken description];
pushToken = [pushToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
[[NSUserDefaults standardUserDefaults] setObject:pushToken forKey:#"device_token_data"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

May be help you.
First register notification in then you will get toke in didRegisterRemoteNotification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
self.strdeviceToken=[[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
self.strdeviceToken = [self.strdeviceToken stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
self.strdeviceToken=[self.strdeviceToken stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
}

You should check your provisioning profile. Also the App should be configured for push notification on developer portal.
Perform these steps for doing so.
Enable push notification for your Application Identifier on Developer portal.
regenerate the provisioning profile.
Download and install new provisioning profile.
Build and run.
It will work.

try this one..
after your transactions completed, you want token number in the view controller. so for that try to make or change root view controller again in appDelegate by the method like this in AppDelegate.m.
-(void)changeRootView
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
//Adding navigation controller to the main view.
[navigationController release];
navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
}
in this method
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
this statement is helped to call didRegisterForRemoteNotificationsWithDeviceToken again and you can store the token in some object like NSUserDefaults and you can use it in your viewController. It works for me. you can try this. Best luck.

Related

Redirect UIAlertView Button Push Notifications

I have read many posts on this matter, but none of them really helps me out. It seems quite easy to do, but somehow I can't figure it out.
What am I trying to do here?
Well, I send a push notifications to my app. Everything works fine.
I can handle it when it is in the background, inactive or even when the app is not running.
But one other state - app in foreground - gives me a headache.
I have this code snippet which I'm using. All fine.
When the app is running in the foreground, the user gets the UIAlertview.
But how do I add an action to the view button?
This particular action I mean: when someone taps the view button he/she gets redirected to the url which has been passed through the push notification.
Just like I have used before in the code snippet (this part to be precise):
NSString *notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
I hope this makes sense and someone can help me out. I'm lost at this one ... This is the entire code snippet which is relevant at this subject.
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
/**
* Remote Notification Received while application was open.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
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);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
NSString *notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
// app was already in the foreground
if ( application.applicationState == UIApplicationStateActive ) {
UIAlertView *alertPush = [[UIAlertView alloc]initWithTitle: #"Message"
message: alert
delegate: self
cancelButtonTitle:#"View"
otherButtonTitles: #"Cancel", nil];
[alertPush show];
[alertPush release];
}
// app is inactive or in the background
else {
[self Redirect:notifUrl];
}
#endif
}
// what to do if user taps the viewbutton in push notification alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(#"View Button has been tapped");
// We need the url that has been passed by the push notification
}
else {
// Do something
}
}
Just define your variable notifUrl in .h file so that you can access this in other methods of your class as well. Then store url in that variable and use that in alertview delegate method.
//Add this in .h file
NSString *notifUrl;
//Add this in .m file
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
/**
* Remote Notification Received while application was open.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
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);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
//Define this variable in .h file so that you can access this in other methods as well
notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
[notifUrl retain]; // this is retain value of notifUrl so that you can use it later
// app was already in the foreground
if ( application.applicationState == UIApplicationStateActive ) {
UIAlertView *alertPush = [[UIAlertView alloc]initWithTitle: #"Message"
message: alert
delegate: self
cancelButtonTitle:#"View"
otherButtonTitles: #"Cancel", nil];
[alertPush show];
[alertPush release];
}
// app is inactive or in the background
else {
[self Redirect:notifUrl];
}
#endif
}
// what to do if user taps the viewbutton in push notification alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(#"View Button has been tapped");
NSLog(#"Received Push Url: %#", notifUrl);
[self Redirect:notifUrl];
}
else {
// Do something
}
}

passing appdelegate data to viewcontroller

I have the following method in my AppDelegate.m. I want the value of deviceToken in my UIViewController
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
ViewController *viewController = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
viewController.tokenStr = [NSString stringWithFormat:#"%#",deviceToken];
}
but when I display NSLog(#"%#",tokenStr); in UIViewController I'm getting (NULL).
how can I get the value in my UIViewController?
In AppDelegate, you can save the deviceToken value in NSUserDefaults like
[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:#"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
and Retrieve that value from any View Controller using
[[NSUserDefaults standardUserDefaults] objectForKey:#"DeviceToken"];
You can have a reference to AppDelegate with [UIApplication sharedApplication].delegate.
It depends on your needs. Something like a token you really should save in NSUserDefaults, it was designed for saving user's credentials and tokens. But if you want to use all public properties and methods of AppDelegate in any viewController, you can use it's delegate.
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *token = appDelegate.token;
In AppDelegate.m class:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(#"My token is: %#", deviceToken);
NSString *device = [deviceToken description];
device = [device stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
device = [device stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"My device is: %#", device);
[[NSUserDefaults standardUserDefaults] setObject:device forKey:#"MyAppDeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
In ViewController class, inside viewDidLoad method:
[super viewDidLoad];
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"MyAppDeviceToken"];
NSLog(#"device token in controller: %# ", deviceToken);
This is working perfectly in my device. Happy Coding !! :)

NSUserDefaults remember view

My App contains a couple of views, I would like to display a small setup when the app launches and the user didn't complete the wizard yet.
I know I can achieve this with NSUserDefaults, But I'm unsure how I can make it to display a specific view depending on the input string of the NSUserDefaults storage.
My AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString *controllerName = [[NSUserDefaults standardUserDefaults] objectForKey:#"WIZARD_VIEW"];
if ([controllerName length]) {
Class controllerClass = NSClassFromString(controllerName);
UIViewController *controller = [[controllerClass alloc] init];
// Override point for customization after application launch.
return YES;
}
Then in the viewcontroller files I added the following code as suggestion from jfaller:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSUserDefaults* standard=[NSUserDefaults standardUserDefaults];
[standard registerDefaults: #{ #"WIZARD_VIEW" : [[self class]description]} ]; [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSUserDefaults* standard=[NSUserDefaults standardUserDefaults];
[standard registerDefaults: #{ #"WIZARD_VIEW" : [[self class]description]} ];
[[NSUserDefaults standardUserDefaults] synchronize];
}
But how can I make this so it will display the specific view that has been selected in the setup?
Personally, I would do the following:
Every time a user goes to a new view in your wizard, record the UIViewController in the user defaults:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSUserDefaults standardUserDefaults] setObject:[[self class] description] forKey:WIZARD_VIEW];
[[NSUserDefault standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:WIZARD_VIEW];
[[NSUserDefault standardUserDefaults] synchronize];
}
When the user restarts the app (hypothetically in the middle of the wizard), reload the view:
- (BOOL)application:(UIApplication *)application
willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// etc.
NSString *controllerName = [[NSUserDefaults standardUserDefaults] objectForKey:WIZARD_VIEW];
if ([controllerName length]) {
Class controllerClass = NSClassFromString(controllerName);
NSViewController *controller = [[controllerClass alloc] init];
// push the controller, or whatever....
}
// etc.
}
Write the view you are on to NSUserDefaults as the view loads. Then check for the value in didFinishLaunchingWithOptions.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([[[NSUserDefaults standardUserDefaults] valueForKey:#"current_setup"] isEqualToString:#"1"]) {
//on view 1!
}
}

Push Notification Badges not Coming

I am using this coding for apple push notification, push notifications are coming but they are coming without any badges, any suggestion what is wrong with this code, that I am not getting badges. I already check the setting tab, and badges are on there.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound)];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken1 {
NSString *str = [NSString
stringWithFormat:#"%#",deviceToken1];
NSLog(#"%#",str);
self.deviceToken = [NSString stringWithFormat:#"%#",str];
NSLog(#"dev --- %#",self.deviceToken);
self.deviceToken = [self.deviceToken stringByReplacingOccurrencesOfString:#"<" withString:#""];
self.deviceToken = [self.deviceToken stringByReplacingOccurrencesOfString:#" " withString:#""];
self.deviceToken = [self.deviceToken stringByReplacingOccurrencesOfString:#">" withString:#""];
NSLog(#"dev --- %#",self.deviceToken);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: #"Error: %#", err];
NSLog(#"%#",str);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"Received notification: %#", userInfo);
//[self addMessageFromRemoteNotification:userInfo];
NSString* alertValue = [[userInfo valueForKey:#"aps"] valueForKey:#"badge"];
NSLog(#"my message-- %#",alertValue);
int badgeValue= [alertValue intValue];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeValue];
}
There was a problem with my server side coding as I just find out that badge value has to be implicitly set as integer to get desired result.
As I'm getting null value in badge value.
I have faced this issue before , hope this helps
{"aps":{"alert":"dsfdsfsdfsdfsdfdfdfsdfsdf","badge":1,"sound":"a"}}
make sure there is no double quotation mark on badge value

Push Notification Device Token?

How to get Device Token from my iPhone Device?
this method will print the deviceToken in console in debug mode, if you want to see the device token you can see in UIAlert also.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APN device token: %#", deviceToken);
NSString *deviceTokenString = [NSString stringWithFormat:#"%#",deviceToken];
UIAlertView *deviceTokenAlert = [[UIAlertView alloc] initWithTitle:#"Device Token"
message:deviceTokenString
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
}
If you have implemented this method
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
}
for Push Notification then you will get the device token (This method is actually one of the two methods that you require to implement in the application)
This might find it useful http://urbanairship.com/docs/push.html
you can also look at Push Notification in Iphone application
I hope you find this useful.
This method will show your device token in console.
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString
stringWithFormat:#"%#",deviceToken];
NSString *newString = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"<" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#">" withString:#""];
[[NSUserDefaults standardUserDefaults] setObject:newString forKey:#"deviceToken"];
NSLog(#"Your deviceToken ---> %#",newString);
}