How to convert NSUUID to NSData
Asked Answered
L

3

11

I need to get NSData from vendorIdentifier without converting to NSString, clear bytes. How to convert NSUUID using getUUIDBytes: to NSData?

Lebbie answered 3/10, 2013 at 23:8 Comment(0)
L
21
NSUUID *vendorIdentifier = [[UIDevice currentDevice] identifierForVendor];
uuid_t uuid;
[vendorIdentifier getUUIDBytes:uuid];

NSData *vendorData = [NSData dataWithBytes:uuid length:16];
Lebbie answered 3/10, 2013 at 23:12 Comment(0)
P
8

Use this to get the vendorIdentifier as Data (Swift 4):

var uuidBytes = UIDevice.current.identifierForVendor!.uuid
let uuidData = NSData(bytes: &uuidBytes, length: 16) as Data

Keep in mind to guard against UIDevice.current.identifierForVendor being nil as the documentation says.


Original answer (Swift 2 Version):

var uuidBytes: [UInt8] = [UInt8](count: 16, repeatedValue: 0)
UIDevice.currentDevice().identifierForVendor!.getUUIDBytes(&uuidBytes)
let uuidData = NSData(bytes: &uuidBytes, length: 16)
Pili answered 16/10, 2015 at 21:7 Comment(0)
C
1

Swift 3 Version:

let vendorId = UIDevice.current.identifierForVendor!
let uuidBytes = Mirror(reflecting: vendorId.uuid).children.map { $0.1 as! UInt8 }
let data = Data(bytes: uuidBytes)
Clearheaded answered 28/2, 2017 at 23:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.