iOS
[swift3] convert Dictionary to Data, Data to String in swift3
aggapple
2017. 5. 29. 13:15
1. Dictionary to Data
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
2. Data to Dictionary
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]
3. String to Data
var somedata = testString.data(using: String.Encoding.utf8)
4. Data to String
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
5. JsonString to Data
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
6. jsonData to Dictionary
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}