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
NSPropertyListSerialization may be an alternative solution.
// Swift Dictionary To Data.
var data = try NSPropertyListSerialization.dataWithPropertyList(dictionaryExample, format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0)
// Data to Swift Dictionary
var dicFromData = (try NSPropertyListSerialization.propertyListWithData(data, options: NSPropertyListReadOptions.Immutable, format: nil)) as! Dictionary<String, AnyObject>
Swift 5
as @yuyeqingshan said, PropertyListSerialization
is a good option
// Swift Dictionary To Data.
do {
let data = try PropertyListSerialization.data(fromPropertyList: [:], format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
// do sth
} catch{
print(error)
}
// Data to Swift Dictionary
do {
let dicFromData = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil)
if let dict = dicFromData as? [String: Any]{
// do sth
}
} catch{
print(error)
}
For Swift 3:
let data = try PropertyListSerialization.data(fromPropertyList: authResponse, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
Leo's answer gave me build time errors because NSData
isn't the same as Data
. The function unarchiveObject(with:)
takes a variable of type Data
, whereas the function unarchiveTopLevelObjectWithData()
takes a variable of type NSData
.
This is a working Swift 3 answer:
var names : NSDictionary = ["name":["John Smith"], "age": 35]
let namesData : NSData = NSKeyedArchiver.archivedData(withRootObject: names) as NSData
do{
let backToNames = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(namesData) as! NSDictionary
print(backToNames)
}catch{
print("Unable to successfully convert NSData to NSDictionary")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With