user6631218
user6631218

Reputation:

how to get iphone device token in ios 9

I want to practice APNS , so I need to get device token.
However,I use my iphone 5 can't get device token.
When I use another iphone that is updated ios10 get device token successfully.
What should I do?

This is my code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //APNS setting

if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]){

    UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [application registerUserNotificationSettings:mySettings];
    [application registerForRemoteNotifications];
}
}


-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

NSString *key = @"once";

BOOL onceShowed = [[NSUserDefaults standardUserDefaults] boolForKey:key];
if ( !onceShowed ){
      // upload device token to my sever      
}
}


-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{

[application registerForRemoteNotifications];
}


Thanks!

Upvotes: 1

Views: 1742

Answers (1)

Sreenath S
Sreenath S

Reputation: 729

Step 1: Register for Push Notification in https://developer.apple.com/notifications/

Step 2: Try this Code.

(BOOL)application:(UIApplication *)application 
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{    
  if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
  {
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
  }
  else
  {
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
  }

- (void)application:(UIApplication *)application 
didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
  NSLog(@"deviceToken: %@", deviceToken);
  NSString * token = [NSString stringWithFormat:@"%@", deviceToken];
  //Format token as you need:
  token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
  token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
  token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
}

Upvotes: 1

Related Questions