我需要在我正在开发的 swift 应用程序中发出 API 请求,要求是,它需要进行 json 编码,然后进行 Base 64 编码。
我以为我已经弄清楚了,但我在 Xcode 中收到错误消息
Cannot assign value of type 'String' to type 'Data?'
这是我正在做的事情的简化版本...
let params: [String: Any] = ["connection_id": 123456]
var request = URLRequest(url: url!) //url is stored as a variable in my class
let jsonData = try? JSONSerialization.data(withJSONObject: params)
request.httpMethod = "POST"
request.httpBody = Data(jsonData!).base64EncodedString() //<--This is where the error is
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
//send out the request with URLSession.shared.dataTask
如果 Xcode 告诉我类型必须是 Data,我如何才能将 json 对象的 base64 编码字符串作为请求中的参数?
最佳答案
当 httpBody 需要 Data
时,
base64EncodedString
返回一个字符串。您只需使用 base64EncodedData
即可。
另外,请注意,天哪,这段代码很危险。这么多强制展开(使用感叹号)。我建议学习如何避免在绝大多数地方使用强制展开。
编辑:由于它返回可选数据,因此您需要将其解包。相对于强制展开的一个微小改进是提供一个默认值作为空主体:
request.httpBody = jsonData?.base64EncodedData() ?? Data()
关于json - Base64Encoded JSON 数据作为 swift 5 中 URLRequest 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57118431/