NSDictionary to NSData and NSData to NSDictionary in Swift

IanTimmis picture IanTimmis · Oct 15, 2014 · Viewed 79.5k times · Source

I am not sure if I am using the dictionary or the data object or both incorrectly. I m trying to get used to the switch to swift but I'm having a little trouble.

var dictionaryExample : [String:AnyObject] =
    ["user":"UserName",
     "pass":"password",
    "token":"0123456789",
    "image":0] // image should be either NSData or empty

let dataExample : NSData = dictionaryExample as NSData

I need the NSDictionary to encode to an NSData object as well as taking that NSData object and decode it into a NSDictionary.

Any help is greatly appreciated, thanks.

Answer

Leo picture Leo · Oct 15, 2014

You can use NSKeyedArchiver and NSKeyedUnarchiver

Example for swift 2.0+

var dictionaryExample : [String:AnyObject] = ["user":"UserName", "pass":"password", "token":"0123456789", "image":0]
let dataExample : NSData = NSKeyedArchiver.archivedDataWithRootObject(dictionaryExample)
let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample)! as? NSDictionary

Swift3.0

let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]

Screenshot of playground

enter image description here