Encoding an UIImage as a Base64 string works on the device, but transferring the string to the server somehow corrupts the string and prevents the server from successfully decoding the image.
Any suggestions on the problem?
// Define params
params["thumbnail_base64"] = imageToBase64(blockSet.thumbnailURL)
...
// Convert params -> query string
let postString = buildQueryString(params)
// Define upload URL
let uploadURL = NSURL(string: RootURL + UploadFilePath)!
// Hit server
let request = NSMutableURLRequest(URL: uploadURL)
request.HTTPMethod = "POST"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
...
private func buildQueryString(parameters: [String:String], omitQuestionMark: Bool = false) -> String {
var urlVars = [String]()
for (k, var v) in parameters {
v = v.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
urlVars += [k + "=" + "\(v)"]
}
return ((urlVars.isEmpty || omitQuestionMark) ? "" : "?") + urlVars.joinWithSeparator("&")
}
private func imageToBase64(filename: String) -> String {
// Get image path
let imagePath = getFilePath(filename)
// Convert image to base64 or return empty string
if let imageData = NSData(contentsOfFile: imagePath) {
let base64String = imageData.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)
return base64String
} else {
printError("Error converting image to Base64: missing image. Filename: \(filename)")
return ""
}
}