Generar un UUID en iOS desde Swift


En mi aplicación Swift de iOS quiero generar cadenas UUID (GUID) aleatorias para usar como clave de tabla, y este fragmento aparece para funcionar:

let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil))

Es esto seguro?

¿O hay quizás un mejor enfoque (recomendado)?

Author: Josh Caswell, 2014-06-26

5 answers

Prueba este:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3

let uuid = UUID().uuidString
print(uuid)
 499
Author: Ahmed Al Hafoudh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-08 12:14:52

También puedes usar la API NSUUID:

let uuid = NSUUID()

Si desea recuperar el valor de la cadena, puede usar uuid.UUIDString.

Tenga en cuenta que NSUUID está disponible desde iOS 6 en adelante.

 27
Author: James Frost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-26 10:45:27

Para Swift 4;

let uuid = NSUUID().uuidString.lowercased()
 12
Author: Celil Bozkurt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-03 21:20:59

Para Swift 3, muchos tipos Foundation han eliminado el prefijo 'NS', por lo que accederías a él por UUID().uuidString.

 10
Author: Scott H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-29 21:38:42

También can úsalo lowercase debajo de

let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)

Salida

68b696d7-320b-4402-a412-d9cee10fc6a3

¡Gracias !

 5
Author: SwiftDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-26 11:19:53