Search code examples
iosjsonswiftbase64alamofire

base64EncodedString returns undesired backslashes


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 (/) with a backslash (becoming \/). For example, the string data:image/jpeg;base64, at the beginning becomes:

data:image\/jpeg;base64,

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.

    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
        }
    }

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

{
    "AVATAR": {
        "base64": "data:image\/jpeg;base64,\/9j\/4AAQSkZJRgABAQAAkACQAAD\/4QC..."
    }
}

where all slashes were escaped.

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

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

Solution

  • I ended using the custom JSONEncoder posted by csim at this answer: Alamofire 5 Escaping Forward Slashes.

    I had to create a new class, using the code provided by csim, and then the Alamofire request became:

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