You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS应用卸载重装后唯一标识符变更,如何获取固定唯一ID?

iOS 获取卸载重装后仍固定的唯一设备ID

你的代码存在两个核心问题,导致卸载重装后ID变更:

  • UIDevice.CurrentDevice.IdentifierForVendor:苹果设计这个标识符就是在应用卸载重装后会重置,无法作为持久ID使用
  • NSUserDefaults:存储的内容会随应用卸载被彻底清除,重装后无法读取旧值,只能生成新的Guid

可行解决方案:用Keychain存储自定义UUID

iOS的Keychain存储在应用卸载后(同一开发者账号签名的应用)会保留数据,是目前唯一能实现卸载重装后ID固定的合法方式。

1. 封装Keychain操作辅助类

using Foundation;
using Security;

public static class KeychainHelper
{
    // 从Keychain读取字符串
    public static string GetString(string key)
    {
        var query = new SecRecord(SecKind.GenericPassword)
        {
            Service = NSBundle.MainBundle.BundleIdentifier,
            Account = key
        };

        SecStatusCode status;
        var data = SecKeyChain.QueryAsData(query, out status);
        if (status == SecStatusCode.Success && data != null)
        {
            return NSString.FromData(data, NSStringEncoding.UTF8);
        }
        return null;
    }

    // 将字符串写入Keychain
    public static void SetString(string key, string value)
    {
        // 先移除已有记录避免冲突
        var existingRecord = new SecRecord(SecKind.GenericPassword)
        {
            Service = NSBundle.MainBundle.BundleIdentifier,
            Account = key
        };
        SecKeyChain.Remove(existingRecord);

        var newRecord = new SecRecord(SecKind.GenericPassword)
        {
            Service = NSBundle.MainBundle.BundleIdentifier,
            Account = key,
            ValueData = NSData.FromString(value, NSStringEncoding.UTF8)
        };
        SecKeyChain.Add(newRecord);
    }
}

2. 修改你的ID生成逻辑

string uuidKey = "myDeviceUUID";
string bundleId = NSBundle.MainBundle.BundleIdentifier;
string uuid = KeychainHelper.GetString(uuidKey);

// 首次启动或Keychain无记录时生成新Guid并存储
if (uuid == null)
{
    uuid = Guid.NewGuid().ToString();
    KeychainHelper.SetString(uuidKey, uuid);
}

string uniqueId = $"{bundleId}-{uuid}";

// 同步到Xamarin.Forms的Properties方便跨平台使用
Xamarin.Forms.Application.Current.Properties["DeviceId"] = uniqueId;
await Xamarin.Forms.Application.Current.SavePropertiesAsync();

注意事项

  • 仅同一开发者账号签名的应用才能共享Keychain数据,不同账号的应用无法读取
  • 如果用户重置设备、抹掉所有内容,Keychain数据会被清空,此时会生成新ID,这是iOS隐私限制下无法避免的情况
  • 苹果已完全禁止使用UDID等设备级固定标识符,不要尝试绕过隐私规则

内容的提问来源于stack exchange,提问作者Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:52:30