UUID返回nil

时间:2017-07-24 17:17:40

标签: ios xcode

我正在尝试获取唯一标识符,但我总是得到一个零值。

static NSString* UUID_KEY = @"CDVUUID"
NSString* app_uuid = [userDefaults stringForKey:UUID_KEY];
NSLog(@"udd:%@",app_uuid);

2 个答案:

答案 0 :(得分:1)

您只是从Userdefaults获取它,它仅用于保存信息并检索它。它不会生成您的UUID。因此,如果您以前从未使用密钥“ CDVUUID ”保存它,则代码将始终为nil,因为在用户默认值中没有为密钥 CDVUUID

生成UUID -

NSString* app_uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; 

NSString *UUID = [[NSUUID UUID] UUIDString];

然后,您可以将其保存在Userdefaults中,然后在用户默认需要时从稍后检索它。

答案 1 :(得分:0)

看起来您从CDVDevice.m复制了此代码,但您只复制了部分代码。

如果UUID不存在,则创建并保存UUID的整个函数是:

- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device
{
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    static NSString* UUID_KEY = @"CDVUUID";

    // Check user defaults first to maintain backwards compaitibility with previous versions
    // which didn't user identifierForVendor
    NSString* app_uuid = [userDefaults stringForKey:UUID_KEY];
    if (app_uuid == nil) {
        if ([device respondsToSelector:@selector(identifierForVendor)]) {
            app_uuid = [[device identifierForVendor] UUIDString];
        } else {
            CFUUIDRef uuid = CFUUIDCreate(NULL);
            app_uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);
            CFRelease(uuid);
        }

        [userDefaults setObject:app_uuid forKey:UUID_KEY];
        [userDefaults synchronize];
    }

    return app_uuid;
}