How to get unique device id in iOS

删除回忆录丶 提交于 2019-12-11 07:38:19

问题


I am working on iOS app for push notification feature i need to send unique device id of iOS device to server ,in android secure androd id getting for every device,is there any way to get unique device id of iOS. I found some answers vendor id and ad id are they unique

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

回答1:


For get UUID you can use this code

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

But for push notifications you need device token and it will create after user will accept permission and UIApplication delegate method will call

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



回答2:


There is no legal way to uniquely identify an iOS device. Period.

You can get only compromise solutions: IDFA, Vendor ID or APNS Device Token. Every above-mentioned ID can change during the device lifecycle, thus they cannot be used as unique device identifiers.




回答3:


for Step by step by Step Integration of APNS in your application , you can get the steps in here

iOS9 Apple says that Device Token might change each time your app is installed. So the best way is to reregister the Device token on each launch.

Step-1

There are two steps to register for push notifications. First, you must obtain the user’s permission to show any kind of notification, after which you can register for remote notifications. If all goes well, the system will then provide you with a device token, which you can think of as an “address” to this device.

This method creates an instance of UIUserNotificationSettings and passes it to registerUserNotificationSettings(_:). UIUserNotificationSettings stores settings for the type of notification your app will use. For the UIUserNotificationTypes, you can use any combination of the following:

  1. .Badge allows the app to display a number on the corner of the app’s icon.

  2. .Sound allows the app to play a sound.

  3. .Alert allows the app to display text.

The set of UIUserNotificationCategorys that you currently pass nil to allows you to specify different categories of notifications your app can handle. This becomes necessary when you want to implement actionable notifications, which you will use later

- (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];
}

Build and run. When the app launches, you should receive a prompt that asks for permission to send you notifications:

Tap OK and poof! The app can now display notifications.

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

Here, you first check whether the user has granted you any notification permissions; if they have, you directly call registerForRemoteNotifications(). Again, methods in UIApplicationDelegate are called to inform you about the status of 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
}

As the names suggest, the system calls application(:didRegisterForRemoteNotificationsWithDeviceToken:) when the registration is successful, and otherwise calls application(:didFailToRegisterForRemoteNotificationsWithError:).

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

Swift

 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)")
}
}

for more information you get in Apple Documents




回答4:


For Objectice-C:

UIDevice *device = [UIDevice currentDevice];

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

For Swift:

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



回答5:


As per the Apple Documentation,

Device tokens can change, so your app needs to reregister every time it is launched and pass the received token back to your server. If you fail to update the device token, remote notifications might not make their way to the user’s device. Device tokens always change when the user restores backup data to a new device or computer or reinstalls the operating system. When migrating data to a new device or computer, the user must launch your app once before remote notifications can be delivered to that device.

Never cache a device token; always get the token from the system whenever you need it. If your app previously registered for remote notifications, calling the registerForRemoteNotifications method again does not incur any additional overhead, and iOS returns the existing device token to your app delegate immediately. In addition, iOS calls your delegate method any time the device token changes, not just in response to your app registering or re-registering.

So the best way is to re-register for the token on each launch. For that you can call registerForPushNotifications(application) in applicationDidFinishLaunching() method.

The delegate method for the above method is didRegisterForRemoteNotificationsWithDeviceToken in which you can the deviceToken and send it to server.

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:


You should receiver in

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

Or if you want to get unique device id , you can use

let UUID = NSUUID().UUIDString



回答7:


as I did in my app, you can use first generated uuid and save it in Keychain file to use it as unique device id (because uuid is changed in every running for ur app and also device token) so u can save a uuid or any custom id u generate in keychain it will remain forever even user uninstall and in install the app many times



来源:https://stackoverflow.com/questions/39265253/how-to-get-unique-device-id-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!