使用Alamofire编码JPEG为Base64时出现多余反斜杠问题求助
Hey there! I’ve dealt with this exact frustration before—let’s get this sorted out for you.
What’s Going On
When you send your Base64-encoded image via Alamofire’s default JSON serialization, the framework automatically escapes special characters like / into \/ as part of standard JSON formatting. While this is technically valid JSON, some backend systems don’t properly unescape these characters, leading to broken Base64 strings that can’t be decoded.
The Solutions
1. Use a Custom JSON Encoder (Recommended for Modern iOS/macOS)
Starting with iOS 13, macOS 10.15, and corresponding Apple platforms, JSONEncoder has an option to disable slash escaping. Just configure your encoder and pass it to Alamofire:
// Create a custom encoder that doesn't escape slashes let jsonEncoder = JSONEncoder() jsonEncoder.outputFormatting = .withoutEscapingSlashes // Your parameters including the Base64 string let requestParameters: [String: Any] = [ "image_data": imageBase64 ] // Send the request with the custom encoder AF.request("your-backend-endpoint", method: .post, parameters: requestParameters, encoder: JSONParameterEncoder(encoder: jsonEncoder)) .responseJSON { response in // Handle your response here }
This tells Alamofire to output JSON without escaping / characters, so your Base64 string stays intact.
2. For Older OS Versions (Workaround)
If you need to support systems older than iOS 13, you can manually serialize your parameters to JSON data with a custom approach that avoids slash escaping, then send the raw data:
do { let parameters: [String: Any] = ["image_data": imageBase64] // Serialize parameters to JSON data let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: []) // Convert data to string and fix escaped slashes if var jsonString = String(data: jsonData, encoding: .utf8) { jsonString = jsonString.replacingOccurrences(of: "\\/", with: "/") let modifiedJsonData = jsonString.data(using: .utf8)! // Send the raw JSON data with correct content type AF.request("your-backend-endpoint", method: .post, data: modifiedJsonData, headers: ["Content-Type": "application/json"]) .responseJSON { response in // Handle response } } } catch { print("JSON serialization error: \(error)") }
Note: This is a workaround—ideally, you should update to using the modern JSONEncoder if possible.
A Quick Side Note
If you have control over the backend, it’s worth fixing the JSON parsing logic to handle escaped slashes (\/) correctly. This is standard JSON syntax, and most modern backend frameworks support it out of the box.
内容的提问来源于stack exchange,提问作者Felipe Ferri

