我这样称呼POST方法
let parameters = ["empId": "1", "empName": "John"]
guard let url = URL(string: "test.com") else {
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch {
}
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let data = data, let response = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] {
print(response)
}
}.resume()
有效。现在,我需要另外将名称为image的图像发送到类型为image/png
的服务器。我该怎么办?
答案 0 :(得分:0)
如果您使用 Alamofire , ObjectMapper
这些示例是发送图像,字符串。
func requestMultipart<T: Mappable>(
method: HTTPMethod,
_ URLString: URLConvertible,
parameters: [String: String]? = nil,
images: [String: Data],
encoding: Alamofire.ParameterEncoding = URLEncoding.default,
success: @escaping (T) -> Void,
failure: @escaping (Error) -> Void
) {
Alamofire
.SessionManager
.default
.upload(
multipartFormData: { multipartFormData in
if !images.isEmpty {
images.forEach { (data) in
multipartFormData.append(
data.value,
withName: data.key,
fileName: data.key + ".jpeg",
mimeType: "image/jpeg"
)
}
parameters?.forEach { (params) in
multipartFormData.append(
params.value.data(
using: String.Encoding.utf8,
allowLossyConversion: false
)!,
withName: params.key
)
}
},
to: URLString,
method: method,
headers: header,
encodingCompletion: { encodingResult in
// handle
}
)
答案 1 :(得分:0)
我不确定您的后端如何读取您的响应,但是通常支持的服务使用多部分数据
请参阅以下链接获取多部分数据: Upload image with parameters in Swift