EEYatHo 앱 깎는 이야기

Swift ) Dictionary, JSONString, Data - EEYatHo iOS 본문

iOS, Swift

Swift ) Dictionary, JSONString, Data - EEYatHo iOS

EEYatHo 2021. 10. 4. 15:28
반응형

Dictionary -> Data 

/// 1
let imageData = UIImage(named: "sissor")?.jpegData(compressionQuality: 0)
let dict: [String: Any] = [
    "string": "bbb",
    "data": imageData,
    "array": ["aaaa", "bbbb", 1234]
]
let dictData = try? PropertyListSerialization.data(fromPropertyList: dict, format: .binary, options: .zero)

/// 2
let jsonData = try? JSONSerialization.data(withJSONObject: dict)

 

Data -> Dictionary

/// 1
let dict = try? PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: .none) as? [String: Any]

/// 2
let dict2 = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]

 

JsonString -> Data

let jsonStr = """
{ \"Key\": \"Value\" }
"""
let jsonData = jsonStr.data(using: .utf8)

 

Data -> JsonString

let jsonString = String(data: data, encoding: .utf8)
Comments