獲取唯一UUID/UDID方案


概述

如何保證獲取到的UUID能夠唯一標識每一台設備呢?我們知道通過UIDevice可以獲取到UUIDString,但是如果App被刪除了然后重新安裝,就會得到不同的UUIDString,這並不是我們希望的。

那么,有什么辦法可以解決這個問題呢?這里不說5.0之前的一切,只說6.0之后的如何做到。

下面提供的只是代碼片段,不是完整的代碼!

案例

蘋果在iOS6.0版本之后,在UIDevice提供了以下屬性:

通過這個屬性,就可以獲取到UUID:

我們來操作一下,先運行某個App,然后打印UUIDString:

然后刪除掉這個App,再重新安裝,然后再打印:

為什么是一樣的呢?不是說會變嗎?是的,因為手機上還安裝了其它跟這個App同屬於同一開發商的App。現在,我們把所有與它是同一開發商的App全部刪除,再重新安裝,再打印如下:

果然發生了變化了。

官方文檔

蘋果官方文檔這么說的:

The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.

The value of this property may be nil if the app is running in the background, before the user has unlocked the device the first time after the device has been restarted. If the value is nil, wait and get the value again later.

The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them. Therefore, if your app stores the value of this property anywhere, you should gracefully handle situations where the identifier changes.

意思大概就是說:

在同一設備上運行來源於同一開發商的App,獲取到的UUIDString屬性是同一個值。當在同一設備上運行來源於不同的開發商的App,所獲取到的UUIDString是不同的。在不同的設備上,不管是否同屬於同一個開發商,得到的UUIDString都會不同。

當設備重啟后,若用戶第一次未解鎖設備,而app在后台運行時,這個UUIDString可能為nil。如果值為nil,請等待並在稍候重新獲取。

當app或者另外來源於同一開發商的app被安裝到同一設備上,這個UUIDString會保持一致(比如上面的小例子,打印出來就是一致的)。當用戶刪除掉設備上所有同一開發商的app后,重新安裝其中某一個app,這時候所獲取到的UUIDString就會發生變化。因此,不管app存儲將這個UUID存儲到哪里,你都應該手動處理這種改變。

那么如何解決這種改變呢?

解決方案

解決方案就是能所生成的UUIDString存儲到KeyChain中,使用同一個access group、同一個identifier。每次獲取UUID,都先從KeyChain中獲取,若為空,則通過UIDevice獲取UUIDString並存儲到KeyChaing,代碼版本如下:

請自行修改~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM