如何在applicationDidBecomeActive中使用deviceToken

时间:2014-02-26 02:26:27

标签: ios objective-c

我可以在这里获取并使用设备令牌:

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

// Prepare the Device Token for Registration (remove spaces and < >)
    NSString *deviceToken = [[[[devToken description]
                               stringByReplacingOccurrencesOfString:@"<"withString:@""]
                              stringByReplacingOccurrencesOfString:@">" withString:@""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];

}

我想在/下使用deviceToken:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
// How To GET/USE device Token Here?
}

3 个答案:

答案 0 :(得分:1)

您可以将设备令牌存储在NSUserDefaults中,所以当您需要它时,您可以轻松获取它,

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

    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

现在,您可以随时随地获取它,直到您的应用程序未被删除。

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    NSString *token=[[NSUserDefaults standardUserDefaults]objectForKey:@"token"];


}

答案 1 :(得分:0)

您可以在appDelegate中添加属性,如下所示: enter image description here

然后你可以在 - (void)应用程序中设置属性:(UIApplication *)应用程序didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken,并在 - (void)applicationDidBecomeActive:(UIApplication *)应用程序中获取属性。

答案 2 :(得分:0)

最佳做法是将deviceToken转换为Base64 NSString,因此您无需解析说明。您可以将此值存储在AppDelegate的私有成员(使用类别)或公共属性中。