IOS7.0惟一「設備ID」的獲取方法

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

相關文章
相關標籤/搜索