簡體   English   中英

如何在iOS中獲取唯一的設備ID

[英]How to get unique device id in iOS

我正在使用iOS應用程序的推送通知功能,我需要將iOS設備的唯一設備ID發送到服務器,在每台設備的Android安全Androd ID獲取中,是否有任何方法可以獲取iOS的唯一設備ID。 我發現一些供應商ID和廣告ID的答案是唯一的

code:
Secure.getString(getContext().getContentResolver(),Secure.ANDROID_ID); 

要獲取UUID,您可以使用此代碼

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

但是對於推送通知,您需要設備令牌,它將在用戶接受權限並且UIApplication委托方法將調用后創建

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

要逐步將APNS集成到您的應用程序中,可以在此處獲取步驟

蘋果公司iOS9表示,每次安裝應用程序時,設備令牌可能都會更改。 因此,最好的方法是在每次啟動時重新注冊設備令牌。

第1步

注冊推送通知有兩個步驟。 首先,您必須獲得用戶的許可才能顯示任何類型的通知,然后您可以注冊遠程通知。 如果一切順利,系統將為您提供設備令牌,您可以將其視為該設備的“地址”。

此方法創建UIUserNotificationSettings的實例,並將其傳遞給registerUserNotificationSettings(_ :)。 UIUserNotificationSettings存儲應用程序將使用的通知類型的設置。 對於UIUserNotificationTypes,可以使用以下任意組合:

  1. .Badge允許應用程序在應用程序圖標的角上顯示一個數字。

  2. .Sound允許該應用播放聲音。

  3. .Alert允許該應用顯示文本。

您當前傳遞nil的一組UIUserNotificationCategorys允許您指定應用程序可以處理的通知的不同類別。 當您要實施可操作的通知時,這是必要的,稍后將使用

- (void)applicationDidFinishLaunching:(UIApplication *)app {
 // other setup tasks here....

// Register the supported interaction types.
UIUserNotificationType types = UIUserNotificationTypeBadge |
             UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings =
            [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

// Register for remote notifications.
[[UIApplication sharedApplication] registerForRemoteNotifications];
}

生成並運行。 應用啟動時,您會收到提示,要求您許可以向您發送通知:

在此處輸入圖片說明

點擊確定,然后po! 該應用程序現在可以顯示通知。

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    if (notificationSettings.types != UIUserNotificationTypeNone) {
        //register to receive notifications
        [application registerForRemoteNotifications];
    } 
}

在這里,您首先要檢查用戶是否已授予您任何通知權限; 如果有,則直接調用registerForRemoteNotifications()。 同樣,將調用UIApplicationDelegate中的方法以通知您有關registerForRemoteNotifications()的狀態。

// Handle remote notification registration.
- (void)application:(UIApplication *)app
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData  *)devToken {
const void *devTokenBytes = [devToken bytes];
self.registered = YES;
 // send your Device Token to server
}

顧名思義, 注冊成功后,系統將調用application( :didRegisterForRemoteNotificationsWithDeviceToken :),否則將調用application( :didFailToRegisterForRemoteNotificationsWithError :)。

- (void)application:(UIApplication *)app
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(@"Error in registration. Error: %@", err);
}

迅速

 let defaults = NSUserDefaults.standardUserDefaults()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // PUSH NOTIFICATION
    let deviceToken = defaults.objectForKey(UserDefaultsContracts.KEY_DEVICE_TOKEN) as String?

    if (deviceToken == nil) {
        print("There is no deviceToken saved yet.")
        var types: UIUserNotificationType = UIUserNotificationType.Badge |
            UIUserNotificationType.Alert |
            UIUserNotificationType.Sound

        var settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil )

        application.registerUserNotificationSettings( settings )
        application.registerForRemoteNotifications()
    }

    return true
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData!) {
    print("Got token data! (deviceToken)")
    var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )

    var deviceTokenString: String = ( deviceToken.description as NSString )
        .stringByTrimmingCharactersInSet( characterSet )
        .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String

    print( deviceTokenString )

    defaults.setObject(deviceTokenString, forKey: UserDefaultsContracts.KEY_DEVICE_TOKEN)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError!) {
    print("Couldn’t register: (error)")
}
}

有關更多信息,請訪問Apple文檔

沒有合法的方法來唯一標識iOS設備。 期。

您只能獲得妥協的解決方案:IDFA,供應商ID或APNS設備令牌。 每個上述ID都可以在設備生命周期中更改,因此它們不能用作唯一的設備標識符。

根據Apple文檔

設備令牌可能會更改,因此您的應用在每次啟動時都需要重新注冊,並將接收到的令牌傳遞回服務器。 如果您無法更新設備令牌,則遠程通知可能不會進入用戶的設備。 當用戶將備份數據還原到新設備或計算機或重新安裝操作系統時,設備令牌始終會更改。 將數據遷移到新設備或計算機時,用戶必須先啟動您的應用程序,然后才能將遠程通知傳遞到該設備。

永遠不要緩存設備令牌; 始終在需要時從系統獲取令牌。 如果您的應用程序先前已注冊用於遠程通知,則再次調用registerForRemoteNotifications方法不會產生任何額外的開銷,iOS會立即將現有設備令牌返回給您的應用程序委托。 此外,iOS會在設備令牌更改時隨時調用您的委托方法,而不僅僅是響應您的應用程序注冊或重新注冊。

因此,最好的方法是在每次啟動時重新注冊令牌。 為此,您可以在applicationDidFinishLaunching()方法中調用registerForPushNotifications(application)

上述方法的委托方法是didRegisterForRemoteNotificationsWithDeviceToken在其中您可以將deviceToken並將其發送到服務器。

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
  let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
  var tokenString = ""

  for i in 0..<deviceToken.length {
    tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
  }

  print("Device Token:", tokenString)
}

對於Objectice-C:

UIDevice *device = [UIDevice currentDevice];

NSString  *currentDeviceId = [[device identifierForVendor]UUIDString];

對於Swift:

let device_id = UIDevice.currentDevice().identifierForVendor?.UUIDString

您應該接收

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    var deviceTokenStr = String(format: "%@", deviceToken)
    deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString("<", withString: "")
    deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString(">", withString: "")
    deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString(" ", withString: "")
}

或者,如果您想獲得唯一的設備ID,則可以使用

let UUID = NSUUID().UUIDString

就像我在應用程序中所做的那樣,您可以使用第一個生成的uuid並將其保存在Keychain文件中,以將其用作唯一的設備ID(因為在每次運行ur app和設備令牌時都會更改uuid),因此您可以保存uuid或其他任何內容您在鑰匙串中生成的自定義ID,即使用戶卸載並多次安裝應用程序也將永久保留

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM