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.
NSPropertyListSerialization may be an alternative solution.
For Swift 4 -
Leo's answer gave me build time errors because
NSData
isn't the same asData
. The functionunarchiveObject(with:)
takes a variable of typeData
, whereas the functionunarchiveTopLevelObjectWithData()
takes a variable of typeNSData
.This is a working Swift 3 answer:
For Swift 3:
You can use
NSKeyedArchiver
andNSKeyedUnarchiver
Example for swift 2.0+
Swift3.0
Screenshot of playground