在IOS中运行ViewController代码之前获取设备ID

时间:2014-02-21 11:40:28

标签: ios objective-c apple-push-notifications

我有这种代码安静来获取设备ID:

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *devicetokenRN = [NSString stringWithFormat:@"%@", deviceToken];
    devicetokenRN = [devicetokenRN stringByReplacingOccurrencesOfString:@" " withString:@""];
    devicetokenRN = [devicetokenRN stringByReplacingOccurrencesOfString:@"<" withString:@""];
    devicetokenRN = [devicetokenRN stringByReplacingOccurrencesOfString:@">" withString:@""];


    // send device token for APNS without spaces or <>
    DeviceID *DeviceIdentifier = [[DeviceID alloc ] init];
    // sending it to the Device.h
    [DeviceIdentifier setDeviceID:devicetokenRN];
}

我需要在ViewController上检索此DeviceID作为第一件事。因为它在运行视图控制器之前不执行此功能,因为如果我在ViewController中使用NSlog它是NULL,因为它没有先运行它。在运行UITableView之前,我需要先得到一些这样的变量。任何想法都会非常棒,谢谢。

2 个答案:

答案 0 :(得分:0)

您可以在NSUserDefaults

中获取并存储 deviceId
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
  NSString *deviceId = [identifierForVendor UUIDString];
  NSUserDefaults *userRegistrarionDetails = [NSUserDefaults standardUserDefaults];
  [userRegistrarionDetails setObject:deviceId forKey:@"deviceID"];
  [userRegistrarionDetails synchronize];
}

你可以通过

获得整个项目的任何地方
NSUserDefaults *userRegistrarionDetails = [NSUserDefaults standardUserDefaults];
NSString * deviceId = [userRegistrarionDetails objectForKey:@"deviceID"];
NSLog(@"%@", deviceId);

答案 1 :(得分:0)

在AppDelegate中,您可以在NSUserDefaults中保存deviceToken值,例如

将这些行放在appdelegate.m中的didRegisterForRemoteNotificationsWithDeviceToken方法中,就像这样

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

{

    [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"DeviceToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

还将这行代码放在您的视图Controller.m和ViewDidLoad方法

并检索该值。

[[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];