NSDictionary to NSData and NSData to NSDictionary in Swift

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.


Solution 1:

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

Solution 2:

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>

Solution 3:

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)
        }