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);
}
Related
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.
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
}
}
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 !! :)
I want show a APNS device token with UILabel.
So I coded below:
//AppDelegate.m
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
// TODO: Pass the token to our server
NSString *devToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSString *str = [NSString
stringWithFormat:#"Device Token=%#",devToken];
UIAlertView *alertCtr = [[UIAlertView alloc] initWithTitle:#"Token is " message:devToken delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
[alertCtr show];
NSLog(#"device token - %#",str);
viewc = [ViewController alloc];
viewc.tokenLabel.text = str;
}
But nothing happend. What's wrong?
viewc = [ViewController alloc];
viewc.tokenLabel.text = str;
After alloc'ing your view controller, you should init it too. And present it, whether modally or in a navigation controller or something else, it's up to you.
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