gpt4 book ai didi

swift - alamofire和URLSession中上传数据key,如何添加?

转载 作者:行者123 更新时间:2023-11-30 11:26:50 24 4
gpt4 key购买 nike

我需要上传数据到服务器,有这个功能

uploadTask(带有请求:URLRequest,来自 bodyData:数据)-> URLSessionUploadTask

alamofire 使用几乎相同的签名

上传(_数据:数据,带有urlRequest:URLRequestConvertible)

知道如何添加名称作为附加数据的键吗?

我见过这个iOS - How to upload a video with uploadTask?在标题中添加文件名,我检查了苹果文档,但它没有说明任何内容

非常感谢

最佳答案

假设您要上传一张名为userImage的图片,那么您可以使用Alamofire的多部分功能。我在这里使用了 SwiftyJSON 。您可以根据自己的要求进行修改。

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
}
}

关于swift - alamofire和URLSession中上传数据key,如何添加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com