[英]Convert Image to Base64 for Json Swift 3
我需要將UIImage
轉換為base64
以在JSON
上發送它。 我的問題是轉換。 我的代碼:
//Proof #1
let base64String = imageData?.base64EncodedData(options: .endLineWithLineFeed)
//Proof #2
let base64String = imageData?.base64EncodedString(options: .endLineWithLineFeed)
let dataJson = ["patient_image": ["title": titleInfo, "description": descriptionInfo, "patient_id": globalID, "images_attributes": ["file": base64String]]]
let url = NSURL(string: "MY_URL")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
request.httpBody = try! JSONSerialization.data(withJSONObject: dataJson, options: .prettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
我嘗試了Swift 3
提供的兩種方法來將圖像轉換為base64
,但是我都遇到相同的錯誤:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
有人可以幫我嗎? 非常感謝您的幫助。
刪除選項:
let base64String = imageData.base64EncodedString()
完整的代碼:
/*
let imageData = Data()
let titleInfo = "test"
let descriptionInfo = "test"
let globalID = "test"
*/
let base64String = imageData.base64EncodedString()
let dataJson = ["patient_image": ["title": titleInfo, "description": descriptionInfo, "patient_id": globalID, "images_attributes": ["file": base64String]]]
let url = NSURL(string: "MY_URL")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
request.httpBody = try! JSONSerialization.data(withJSONObject: dataJson, options: .prettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
同樣(與您的問題無關),鍵名images_attributes
聽起來像需要數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.