ios7.0 之后经过sysctl得到的mac地址已经失效,全部设备均为020000000000.html
能够经过苹果的keychain机制,实现设备的惟一ID标示。ios
具体过程:在app第一次安装时,生成一个惟一的ID,将该ID保存到keychain中。keychain内的id并不会由于app的卸载而失效,下次安装或者更新仍然能够取到这个惟一的ID,从而能够找到这个设备对应的帐号。
注:惟一ID的生成,能够经过程序本身的算法如guid,或者用苹果自带的IDFV([[UIDevice currentDevice]] identifierForVendor]]).算法
如下是具体代码:app
static KeychainItemWrapper * s_pWrapper = Nil; // 获取开发者的ID NSString * getAppID() { NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword, kSecClass, @"bundleSeedID", kSecAttrAccount, @"", kSecAttrService, (id)kCFBooleanTrue, kSecReturnAttributes, nil]; CFDictionaryRef result = nil; OSStatus status = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef *)&result); if (status == errSecItemNotFound) status = SecItemAdd((CFDictionaryRef)query, (CFTypeRef *)&result); if (status != errSecSuccess) return nil; NSString *accessGroup = [(NSDictionary *)result objectForKey:(id)kSecAttrAccessGroup]; NSArray *components = [accessGroup componentsSeparatedByString:@"."]; NSString *bundleSeedID = [[components objectEnumerator] nextObject]; CFRelease(result); return bundleSeedID; } // 获取设备惟一ID std::string getUniqueID() { if (s_pWrapper == Nil) { #if TARGET_IPHONE_SIMULATOR s_pWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAPP" accessGroup:Nil]; #else NSString* boundSeedID = getAppID(); NSString* appID = @".com.YourCompany.YourAPP"; NSString* groupID = [boundSeedID stringByAppendingString:appID]; s_pWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAPP" accessGroup:groupID]; #endif // [s_pWrapper resetKeychainItem]; } // 是否已注册过 NSString *key = [s_pWrapper objectForKey:(id)kSecValueData]; if (key != Nil && key.length > 0) { return [key UTF8String]; } // 7.0系统取IDFV做为惟一标示 NSUUID* uuid = [[UIDevice currentDevice] identifierForVendor]; key = [uuid UUIDString]; // 注册到keychain中 [s_pWrapper setObject:(id)key forKey:(id)kSecAttrAccount]; [s_pWrapper setObject:(id)key forKey:(id)kSecAttrService]; [s_pWrapper setObject:(id)key forKey:(id)kSecValueData]; return [key UTF8String]; }
注:ide
一、KeychainItemWrapper为apple官方提供的一个sample里面的代码,连接https://developer.apple.com/library/ios/samplecode/GenericKeychain/Listings/Classes_KeychainItemWrapper_m.html
二、在项目的Capabilities属性下,将Keychain sharing改为Enable。项目中会自动添加一个entitlements文件。ui