I am trying to get the device token in my AppDelegate, and then use it in a function in my ViewController later.
I successfully retrieve the device token like so in the AppDelegate:
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *tokenAsString = [[[deviceToken description]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]]
stringByReplacingOccurrencesOfString:#" " withString:#""];
[[NSUserDefaults standardUserDefaults] setObject: token forKey:#"deviceToken"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
Then I am trying to use it in a function in my ViewController, but it is printing as null:
-(void)addDeviceToken{
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
NSLog(#"%#", deviceToken);
}
Does anyone know how to get the variable to show up here?
Replace token with tokenAsString.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *tokenAsString = [[[deviceToken description]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]]
stringByReplacingOccurrencesOfString:#" " withString:#""];
[[NSUserDefaults standardUserDefaults] setObject: tokenAsString forKey:#"deviceToken"];
[[NSUserDefaults standardUserDefaults]synchronize];}
Related
I'm getting DeviceToken is nil
Please help me.
Code in AppDelegate is as follows
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *deviceTokenString = [NSString stringWithFormat:#"%#", deviceToken];
NSLog(#"Device token : %#", deviceToken);
[[NSUserDefaults standardUserDefaults] setObject:deviceTokenString forKey:#"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults] setObject:#"1" forKey:#"isNotificationsEnabled"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Code of ViewDidLoad
- (IBAction)NextBtn:(id)sender
{
NSString *getDeviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"DeviceToken"];
NSLog(#"DeviceToken:%#",getDeviceToken);
getDeviceToken = [getDeviceToken stringByReplacingOccurrencesOfString:#"<" withString:#""];
getDeviceToken = [getDeviceToken stringByReplacingOccurrencesOfString:#">" withString:#""];
[service registerWithCounty:[NSString stringWithFormat:#"%ld", (long)country1.Id] andPhoneNumber:self.phNumber andDeviceId:getDeviceToken];
}
The iPhone Simulator cannot receive push notifications or successfully register for them.
You should rather use a device for testing this functionality.
For registering and using PUSH functionality you require a APNS supported provisioning profile which can be utilised/installed on a device only.
Register for RemoteNotification in following method
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { }
with following code
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[[UIApplication sharedApplication] registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
Then implement following method
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSString* strToken = [deviceToken description];
strToken = [strToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
strToken = [strToken stringByReplacingOccurrencesOfString:#" " withString:#""];
[[NSUserDefaults standardUserDefaults] setValue:strToken forKey:#"device_token"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Hi in my application I'm fetching the device token and I'm passing to my server to send the notification now I want to send the individual notification for the i need to fetch the device token form my UIViewController Please tell is there any possibilities fetching the device token form the Appdelegate or from the UIViewController
My code for fetching the device token in Appdelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeNone)];
return YES;
}
Device Token.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(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]];
}
NSString *urlString = [NSString stringWithFormat:#"url?token=%#",token];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSLog(#"token %#",urlString);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSLog(#"request %# ",urlRequest);
NSData *urlData;
NSURLResponse *response;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
NSLog(#"data %#",urlData);
}
I have used the to get the device token please tell me how to pass the device token to my UIViewController or how to fetch the device token from my UIViewController.
Use the NSUserDefaults to store the objects(values), you can access it anywhere.
AppDelegate (setValue) :
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
[[NSUserDefaults standardUserDefaults] setObject: token forKey:#"deviceID"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
UIViewController (getValue) :
[[NSUserDefaults standardUserDefaults] objectForKey:#"deviceID"];
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 !! :)
Try this coding in your view did load
NSString* deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
deviceId = [deviceId stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSLog(#"%#",deviceId);
Declare and define below methods in your delegate file,
#pragma mark - Get / Set Device Token
+ (void)setDeviceToken:(NSString *)token {
if(token) {
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
+ (NSString *)getDeviceToken {
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:#"DeviceToken"];
if(token) {
return token;
}
return #"";
}
In -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken method
call, [AppDelegate setDeviceToken:token]; once you get the token and
Now in project, in any view controller, you can call NSString *token = [AppDelegate getDeviceToken]; to get saved token, here note that, we call it with AppDelegate its name of your delegate file, and we call it with the class name, as we make a class method to set and get a token.
At the time of getting you can check for availability of saved token
NSString *token = [AppDelegate getDeviceToken];
if(token.length) {
// do something
}
You can get appDelegate instance in any view contoller and fetch value from that instance like -
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
I have followed this tutorial http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
As notification has been sent successfully from the server as described in tutorial. But i am not getting it in my device.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
if(![[NSUserDefaults standardUserDefaults] valueForKey:#"UUID"])
{
if (SYSTEM_VERSION_LESS_THAN(#"6.0"))
{
deviceID = [self GetUUID];
}
else
{
NSUUID* udid= [UIDevice currentDevice].identifierForVendor;
deviceID = [udid UUIDString];
}
[[NSUserDefaults standardUserDefaults] setValue:deviceID forKey:#"UUID"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else
{
deviceID = [[NSUserDefaults standardUserDefaults] valueForKey:#"UUID"];
}
return YES; }
- (NSString *)GetUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string; }
For push notifications you have to register with the push notification token. iOS returns the push notification token with spaces, you have to remove them:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[devToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"token: %#", token);
}
Have you implemented application:didReceiveRemoteNotification: in your application delegate? When you're in app notifications get received there.
Or is it no notification gets sent to you?
What's the size of your payload? The maximum length is 256bytes. If your payload is over that limit, it may say the push has been sent successfully yet Apple rejects it silently.
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
i have ios project i xcode and I need to get device token from Appdelegate to view controller, here is code of App delegate:
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:#"token"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
And then, in view controller:
[super viewDidLoad];
[[NSUserDefaults standardUserDefaults] objectForKey:#"token"];
When I try it for the first time, it was working, but next time app crahed... When I remove that code from view controller, it works, so it must be wrong there... Can you help me?
First of all, delete your app from your phone/simulator.
Because the NSUserDefaults may hold wrong data for your key.
then replace your code with these,
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
if(deviceToken){
[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:#"token"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
In viewDidLoad,
- (void)viewDidLoad
{
[super viewDidLoad];
id token = [[NSUserDefaults standardUserDefaults] objectForKey:#"token"];
if(token){
NSLog(#"I have got the token");
}else NSLog(#"no token");
}
Developing for a jailbroken device.
I've looked here for a soultion to my problem. Using NSUserDefaults for storing UISwitch state but people say alot of the codes don't work.
I'm using a UISwitch to load/unload a launch daemon for iOS. I've gotten very close but the switch state won't save. This is the code im using.
#synthesize toggleSwitch;
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([[NSUserDefaults standardUserDefaults] boolForKey:#"switch"]) toggleSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"switch"];
}
- (void)switchValueChanged {
if (toggleSwitch.on) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
switchlabel.text = #"Enabled";
const char *onchar = [[NSString stringWithString:#"launchctl load -wF /System/Library/LaunchDaemons/com.launch.daemon.plist"] UTF8String];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
setuid(0); system(onchar);
if (system(onchar) == 0){
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];}
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
switchlabel.text = #"Disabled";
const char *offchar = [[NSString stringWithString:#"launchctl unload -wF /System/Library/LaunchDaemons/com.launch.daemon.plist"] UTF8String];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
setuid(0); system(offchar);
if (system(offchar) == 0){
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE]; }
}
The bool value is written in my app plist. I don't seem to know what I did wrong. I pieced afew examples from questions on overflow with no luck. Regardless if the command fails, the switch should save.
Could someone explain and show me what should be edited. This has been driving me absolutely nuts.