此错误我无法将jsonObject发送为数据
由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“ JSON写入(_NSInlineData)中的类型无效”
let data = /* type of data */
let dic : NSDictionary = ["ID" : "UserName", "Data" : data]
let jsonData = try? JSONSerialization.data(withJSONObject: dic, options: [])
self!.socket.write(data: jsonData!)
答案 0 :(得分:1)
根据您的数据创建一个字符串,然后可以发送它。
func jsonToString(json: AnyObject) -> String{
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data1, encoding: String.Encoding.utf8)
return convertedString!
} catch let myJSONError {
print(myJSONError)
return ""
}
}
您可以使用它:
let messageString = jsonToString(json: jsonData as AnyObject)
socket.write(string: messageString)