我正在尝试通过multipart/form-data
发送URLSession
请求,我已经写了一个辅助函数来为我创建Data
形式的正文,但是我的请求始终失败,并返回{{ 1}}响应代码。
我正在尝试打印请求的字符串表示形式以确保主体正确,但是现在仅尝试对其进行解码会抛出错误,500
这使我相信我的请求的编码方式有问题。
这本质上是我的设置-
The data couldn’t be read because it isn’t in the correct format.
我调用这样的东西-
struct Media {
let key: String
let filename: String
let data: Data
let mimeType: String
init?(withImage image: UIImage, forKey key: String) {
self.key = key
self.mimeType = "image/jpeg"
self.filename = "avatar.jpg"
guard let data = image.jpegData(compressionQuality: 0.7) else { return nil }
self.data = data
}
}
typealias Parameters = [String: String]
func createFormData(usingParams params: Parameters?, media: [Media]?, boundary: String) -> Data {
let lineBreak = "\r\n"
var body = Data()
if let parameters = params {
for (key, value) in parameters {
body.append(string:"--\(boundary + lineBreak)")
body.append(string:"Content-Disposition: form-data; name=\"\(key)\"\(lineBreak + lineBreak)")
body.append(string:"\(value + lineBreak)")
}
}
if let media = media {
for photo in media {
body.append(string:"--\(boundary + lineBreak)")
body.append(string:"Content-Disposition: form-data; name=\"\(photo.key)\"; filename=\"\(photo.filename)\"\(lineBreak)")
body.append(string:"Content-Type: \(photo.mimeType + lineBreak + lineBreak)")
body.append(photo.data)
body.append(string: lineBreak)
}
}
body.append(string: "--\(boundary)--\(lineBreak)")
return body
}
extension Data {
mutating func append(string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
我尝试使用以下命令打印数据-
let boundary = UUID().uuidString
guard let profilePic = Media(withImage:image, forKey: "file") else { return }
let data = createFormData(usingParams: nil, media: [profilePic], boundary: boundary)
这将引发前面提到的错误。
我也尝试过
do {
print(data)
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
print(json)
} catch let error {
print(error.localizedDescription)
}
这只是返回nil。
我注意到如果删除 let string = String(data: data, encoding: .utf8)
print(string)
,数据现在可以以JSON格式打印出来,但是我不确定为什么这很重要