[英]Upload data key in alamofire and URLSession, how to add it?
I need to upload data to server and There's this function 我需要将数据上传到服务器,并且有此功能
uploadTask(with request: URLRequest, from bodyData: Data) -> URLSessionUploadTask
which alamofire uses with almost same signature alamofire使用的签名几乎相同
upload(_ data: Data, with urlRequest: URLRequestConvertible)
any idea how to add name as a key for the appended data? 任何想法如何添加名称作为附加数据的键?
I've seen this iOS - How to upload a video with uploadTask? 我看过这个iOS-如何使用uploadTask上传视频? adding file name in headers, I've checked apple docs for it and it stated nothing about it
在标头中添加文件名,我已经检查过苹果文档,但没有说明
Thanks a lot 非常感谢
Suppose you want to upload an image with key named as userImage
, then you can use multipart feature of Alamofire
. 假设您要上传一个名为
userImage
键的图像,则可以使用Alamofire
多部分功能。 I have used SwiftyJSON
here. 我在这里使用了
SwiftyJSON
。 You can modify as per your own requirement. 您可以根据自己的要求进行修改。
var parameters: [String:Any]?
//fill your parameters with data. Image is stored as Data and other values are string in this case.
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters! {
if key == "userImage" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "profileImage.jpg",
mimeType: "image/jpg"
)
} else {
//multipartFormData
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
}
}, usingThreshold: 1, to: "yourServiceURL", method: .post, headers: ["yourHeaderkey":"value"]) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
return
}
if let data = response.result.value {
let json = JSON(data)
}
}
break
case .failure(let encodingError):
debugPrint(encodingError)
break
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.