【问题标题】:How to get unique device id in iOS如何在 iOS 中获取唯一的设备 ID
【发布时间】:2017-01-08 23:13:18
【问题描述】:

我正在开发用于推送通知功能的 iOS 应用程序,我需要将 iOS 设备的唯一设备 ID 发送到服务器,在为每个设备获取的 android 安全安卓 ID 中,有没有办法获取 iOS 的唯一设备 ID。 我找到了一些答案 vendor id 和 ad id are they unique

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

【问题讨论】:

  • 生成您自己的标识符并将其保存到钥匙串。如果您想与其他应用共享,请共享钥匙串。

标签: ios objective-c swift deviceid


【解决方案1】:

要获取 UUID,您可以使用此代码

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

但是对于推送通知,您需要设备令牌,它将在用户接受许可后创建,UIApplication 委托方法将调用

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

【讨论】:

  • 正如头文件中的注释所说// a UUID that may be used to uniquely identify the device, same across apps from a single vendor.
  • 用户可以决定应用程序无法访问该标识符。
【解决方案2】:

没有合法的方式来唯一标识 iOS 设备。期间。

您只能获得妥协解决方案:IDFA、供应商 ID 或 APNS 设备令牌。 上述每个 ID 都可以在设备生命周期内发生变化,因此不能用作唯一的设备标识符。

【讨论】:

    【解决方案3】:

    APNS在您的应用程序中的逐步集成,您可以在here中获取步骤

    iOS9 Apple 表示,每次安装您的应用时,设备令牌可能会发生变化。所以最好的方法是在每次启动时重新注册设备令牌。

    第一步

    注册推送通知有两个步骤。首先,您必须获得用户的许可才能显示任何类型的通知,之后您才能注册远程通知。如果一切顺利,系统会为您提供一个设备令牌,您可以将其视为该设备的“地址”。

    此方法创建 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];
    }
    

    构建并运行。当应用启动时,您应该会收到一条提示,要求您允许向您发送通知:

    点击确定,然后噗!该应用现在可以显示通知。

    - (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 Documents

    【讨论】:

    • 如果你建议OP应该使用APNS返回的Device Token来唯一标识设备,那么你应该明确说明你的理由。
    【解决方案4】:

    对于 Objectice-C:

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

    对于斯威夫特:

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

    【讨论】:

      【解决方案5】:

      根据Apple Documentation

      设备令牌可以更改,因此您的应用每次都需要重新注册 它启动并将接收到的令牌传递回您的服务器。如果你 无法更新设备令牌,远程通知可能不会发出 到用户设备的方式。设备令牌总是在 用户将备份数据恢复到新设备或计算机或重新安装 操作系统。将数据迁移到新设备或计算机时, 用户必须先启动您的应用程序,然后才能收到远程通知 传送到该设备。

      从不缓存设备令牌;总是从系统中获取令牌 每当你需要它。如果您的应用之前注册了远程 通知,再次调用 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)
      }
      

      【讨论】:

        【解决方案6】:

        你应该在

        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
        

        【讨论】:

          【解决方案7】:

          就像我在我的应用程序中所做的那样,您可以使用第一个生成的 uuid 并将其保存在钥匙串文件中,以将其用作唯一的设备 ID(因为 uuid 在每次运行您的应用程序和设备令牌时都会更改),因此您可以保存uuid 或您在钥匙串中生成的任何自定义 id,即使用户卸载并多次安装应用程序,它也将永远保留

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-09-07
            • 2014-11-13
            • 1970-01-01
            • 2020-06-15
            • 2020-12-29
            • 2017-01-06
            • 2019-08-28
            • 1970-01-01
            相关资源
            最近更新 更多