2016-12-02 68 views
0

我需要將UIImage轉換爲base64以便將其發送到JSON。我的問題是轉換。我的代碼:將圖像轉換爲Base64 for Json Swift 3

//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)' 

有人可以幫我嗎?我非常感謝你的幫助。

回答

3

刪除的選項:

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聽起來像預計的數組。

+0

let base64String = imageData.base64EncodedString() 很酷,它幫助我很多。但我想知道爲什麼,如果我們使用選項有什麼區別? – HamasN