base64EncodedString returns undesired backslashes

时间:2018-05-06 17:06:31

标签: ios json swift base64 alamofire

I am encoding a JPEG image to Base64 for sending to my app's backend using Alamofire.

When I inspect the sent string using Charles Proxy I find out that the encoded string escapes all slashes (>> startTime = datetime('2014/06/01-00:00', 'InputFormat', 'yyyy/MM/dd-HH:mm') startTime = datetime 01-Jun-2014 00:00:00 >> datestr(startTime, 'yyyy/MM/dd-HH:mm') ans = 2014/00/01-00:06 ) with a backslash (becoming $user->instagram()->delete(); $user->comments()->delete(); ). For example, the string / at the beginning becomes:

\/

As all slashes in the Base64 encoded string, which renders the encoded string unusable.

Here is the code I use for encoding the image. The variable imageBase64 receives the string with the escaped slashes.

data:image/jpeg;base64,

When I send the imageData string to the backend using Alamofire, the json sent in the request body becomes like this:

data:image\/jpeg;base64,

where all slashes were escaped.

The code I use for making the request is the following:

    if let image = image {
        let croppedImage = image.af_imageAspectScaled(toFill: CGSize(width: 500, height: 500))
        if let imageData = UIImageJPEGRepresentation(croppedImage, 0.8) {
            let imageBase64 = "data:image/jpeg;base64,\(imageData.base64EncodedString())"
            base64dict["base64"] = imageBase64 as AnyObject
            bodyParams["AVATAR"] = base64dict as AnyObject
        } else {
            base64dict["base64"] = "null" as AnyObject
            bodyParams["AVATAR"] = base64dict as AnyObject
        }
    }

1 个答案:

答案 0 :(得分:0)

我使用csim发布的自定义JSONEncoder结束了这个答案:Alamofire 5 Escaping Forward Slashes

我必须使用csim提供的代码创建一个新类,然后Alamofire请求变为:

Alamofire.request(finalURL,
    method: method,
    parameters: bodyParams,
    encoding: JSONEncodingWithoutEscapingSlashes.default,
    headers: ["Content-Type": "application/json"])
.responseJSON { response in
    // process response
    }