I have been trying to get JSONEncoder
's dataEncodingStrategy
work.
I need to get my http body data without escaped on API requests and there is this withoutEscapingSlashes: JSONEncoder.OutputFormatting
of JSONEncoder
but unfortunately this is only for iOS >= 13 whereas my app supports iOS >= 11.
This is what I have at the moment:
let encoder = JSONEncoder()
if #available(iOS 13, *) {
encoder.outputFormatting = .withoutEscapingSlashes
} else {
// Fallback to earlier versions here!
// Looking for a workaround and I believe "dataEncodingStrategy" is what I am looking for.
}
try encoder.encode(data)
Here is a simple example from Playground for test purpose to show you what I wrote.
JSONEncoder.DataEncodingStrategy.custom
(that is var strategy) is never called.
import Foundation
struct Model: Encodable {
let key: String = "key goes here..."
}
var strategy: JSONEncoder.DataEncodingStrategy = .custom({ (data, encoder) in
print("CALLED!") // This is never printed.
if var string = String(data: data, encoding: .utf8) {
string = string.replacingOccurrences(of: "key", with: "REPLACED")
var container = encoder.singleValueContainer()
let data = string.data(using: .utf8)
try container.encode(data)
}
})
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = strategy
let m = Model()
let d = try! encoder.encode(m)
let str = String(data: d, encoding: .utf8)
print(str)
dataEncodingStrategy
is always dismissed no matter what. It is never called. It is not deprecated or something. Does anybody know what is going on here?
Although this question is specific to JSONEncoder
's dataEncodingStrategy
, any other approach for keeping http body data without escaped for iOS < 13 would be helpful as well.