我正在通过alamofire网络使用for循环上传多个图像,但是我想不使用for循环上传多个图像。有没有任何方法或方法可以上传多个图像而无需for循环。
答案 0 :(得分:0)
这是我工作中的有效代码,您将需要导入一些必需的类并根据您的Web服务参数更改参数。
func uploadImage(url:String, parameters:Dictionary<String, Any>, images:[UIImage]) {
let URL = url
//print (URL, parameters)
//show uploading
SVProgressHUD.show(withStatus: NSLocalizedString("Uploading Image", comment: "").loadigSuffix())
SVProgressHUD.setDefaultMaskType(.none)
Alamofire.upload(multipartFormData: { multipartFormData in
for image_ in images {
if let imageData = self.serverCompatibleImageData(image: image_) {
//print("final Image size = ", imageData)
multipartFormData.append((imageData), withName: "userfile[]", fileName: "file.jpg", mimeType: "image/jpg")
}
}
for (key, value) in parameters {
let val = String(describing: value)
multipartFormData.append((val.data(using: .utf8))!, withName: key)
}
}, to: URL, method: .post, headers: ["Authorization" : "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
debugPrint("Self does not have the authority here!")
return
}
var serializedData : Any? = nil
var message = NSLocalizedString("Success", comment: "")+"!"//MUST BE CHANGED TO RELEVANT RESPONSES
var success:Bool!
//check content availability and produce serializable response
do {
serializedData = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments)
//debugPrint(message, "Response Dictionary:", serializedData ?? "Data could not be serialized", separator: "\n")
success = true
}catch{
message = NSLocalizedString("Webservice Response error", comment: "")+"!"
let string = String.init(data: response.data!, encoding: .utf8) as String!
success = false
do {
if let s = string?.substring(from: (string?.index(of: "{")!)!) {
if let data = s.data(using: String.Encoding.utf8) {
serializedData = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
debugPrint(message, "_:", serializedData ?? "Data could not be serialized", separator: "\n")
}
}
}catch{
debugPrint(message, error.localizedDescription, "Respone String:", string ?? "No respone value.", separator: "\n")
}
}
//call finised response in all cases
self?.delegate?.uploaded?(succes: success, and: serializedData, message: message)
}
case .failure(let encodingError):
debugPrint("Error:\(encodingError)")
//self.handleImageError()
}
})
}
答案 1 :(得分:0)
代码:
var list = [UIImage]()
func uploadImages(){
if list.isEmpty{
return
}
uploadImage(otherData: [:], image: list.first!)
}
func uploadImage(otherData: [String : String], image: UIImage) {
Alamofire.upload(multipartFormData: { multipartFormData in
let imageData = image.jpegData(compressionQuality: 0.5)
multipartFormData.append(imageData!, withName: "file",fileName: "file.jpg", mimeType: "image/jpg")
for row in otherData{
if !row.value.isEmpty{
multipartFormData.append(row.value.data(using: String.Encoding.utf8)!, withName: row.key)
}
}
},
to: "https://yourwebservice")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseString {response in
self.list.removeFirst()
self.uploadImages()
}
case .failure(let error):
print(error)
}
}
}
您需要一个在类级别声明的图像数组,然后调用uploadImages()函数。此功能将负责启动阵列中所有图像的上传。在服务器成功响应后,我删除了第一个元素,然后再次调用uploadImages()。该过程将继续进行,直到未上传所有图像为止。但是,如果上传失败,此过程将停止。.请参阅失败案例。