Linking user account to device token for push noti

2019-04-30 19:30发布

问题:

I have an app set up with an API server and each user creates an account either by email or facebook when they download the app. That information is all stored in the back end. I want to enable push notifications so that they are user specific. I know what needs to be done on the back end with APNS server etc. My question is linking the Device Token with a user account so I can send the right user the right information based on logic from my servers.

I know that I place this code in the applicationDidFinishLaunching:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

    return YES;
}

And then I grab the device ID from here:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

Am I correct in thinking that when the user signs in I can just send the device token to my server and associate it with that user? I can just add an attribute to the API call to handle that, I just want to make sure that is inline with Apple's expected practices. Then when a user logs out I would just clear the Device Token from their username so that if another user logs in on the same device I wouldn't have a duplicate token.

回答1:

That's exactly what you should do. In didRegisterForRemoteNotificationsWithDeviceToken you can store the device token locally, and then, when the user logs-in, you can send the device token with the user identifier to your server.