Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Device token in push notification

I want to send push notification to certain users only.

From what I have gone through in Apple docs. The code to register for push notification is this

- (void)applicationDidFinishLaunching:(UIApplication *)app {
   // other setup tasks here....
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    const void *devTokenBytes = [devToken bytes];
    self.registered = YES;
    [self sendProviderDeviceToken:devTokenBytes]; // custom method
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error in registration. Error: %@", err);
}

In the method appdidRegisterForRemoteNotif..I see only devToken bytes created and send to the server..but how will I identify which device token belongs to which user. So if my device name is Shubhank's iPhone. How can I send the information that my iPhone is this and this is my device token.

like image 717
Shubhank Avatar asked Jan 17 '23 13:01

Shubhank


1 Answers

generally you don't update the apns token on server in the delegate method itself. you save it and update it later when you have the user identified.

You can do it this way:

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {

const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                      ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                      ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                      ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
[[MyModel sharedModel] setApnsToken:hexToken];

}

with this you saved the apns token in the Model object (MyModel). And later when you have your user identified (by login/sign up or whatever method)

you can call this method

[self sendProvidedDeviceToken: [[MyModel sharedModel] apnsToken] forUserWithId: userId];  //Custom method

This way you have linked the device token with user. Hope this helps!

like image 191
Manish Ahuja Avatar answered Jan 31 '23 11:01

Manish Ahuja