xamarin 每当在设备上卸载和重新安装应用程序时,iOS设备的唯一持久标识符都会更改

42fyovps  于 9个月前  发布在  iOS
关注(0)|答案(1)|浏览(80)

每当在设备上卸载和重新安装应用程序时,iOS设备的唯一持久标识符都会更改。出于隐私考虑,iOS对唯一持久标识符进行了严格限制。
我如何获得唯一的固定身份识别ID?
我正在尝试此代码,但在我卸载应用程序并重新安装后,我的唯一ID发生了变化。

var uuidKey = new NSString("myDeviceUUID");

    string bundleId = NSBundle.MainBundle.BundleIdentifier;
    string uuid = null;

    if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
    {
        uuid = UIDevice.CurrentDevice.IdentifierForVendor.AsString();
    }
    else
    {
        uuid = NSUserDefaults.StandardUserDefaults.StringForKey(uuidKey);
    }
    if (uuid == null)
    {
        uuid = Guid.NewGuid().ToString();
    }

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

    NSUserDefaults.StandardUserDefaults.SetString(uuid, uuidKey);           
    Xamarin.Forms.Application.Current.Properties["DeviceId"] = uniqueId;
    Xamarin.Forms.Application.Current.SavePropertiesAsync();
aamkag61

aamkag611#

你可以通过使用iOS的钥匙链来实现这一点。
这是怎么回事我们将检查设备中是否存在带有我们密钥的现有钥匙链,在这种情况下,它将保存Apple提供的唯一供应商ID。如果存在,这意味着该应用程序之前已经安装在设备中,用户正在重新安装它。因此,我们从之前存储的钥匙串中获取唯一供应商ID。如果密钥不存在,这意味着该用户是第一次在设备中新安装应用程序,因此我们将唯一的供应商ID存储到密钥链中以供以后访问。
注意:如果卸载应用程序,则不会删除钥匙串数据。
AppDeletegate.cs中添加此代码,并在FinishedLaunching之前调用此方法。
SecureStorageXamarin.Essentials封装。
您可以使用依赖项服务来读取UID。在这里,Helpers.DeviceInfo.UID是一个静态字符串,变量名为UID,位于Xamarin.iOS文件夹中Helpers命名空间下的DeviceInfo类中。

/**
     * For iOS devices, for each uninstall and install, there will be a
     * new vendor ID is generated. So in order to identify the device
     * uniquely, we are storing the Vendor Id given by Apple in the
     * device keychain. So if the keychain does not have the unique
     * vendor Id, then we are adding one into the keychain store.
     */
    private async void PrepareVendorIdentifier()
    {
        try
        {
            string uid = await SecureStorage.GetAsync("AppVendorID");

            if (string.IsNullOrEmpty(uid))
            {
                uid = UIDevice.CurrentDevice.IdentifierForVendor.AsString();
                await SecureStorage.SetAsync("AppVendorID", uid);
            }

            Helpers.DeviceInfo.UID = uid;
        }
        catch (Exception)
        {
            Helpers.DeviceInfo.UID = UIDevice.CurrentDevice.IdentifierForVendor.AsString();
        }
    }

希望这对你有帮助。

相关问题