使用alamofire上传多个图像,而不使用swift中的for循环

问题描述 投票:-1回答:2

我正在通过alamofire网络使用for循环上传多个图像,但我想上传多个图像而不使用for循环。是否有任何方法或方法上传多个图像没有for循环。

ios swift alamofire image-uploading
2个回答
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()
        }
    })
}

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()。此过程将继续,直到所有图像都未上传。但是,如果上传失败,此过程将被停止..请参阅失败案例。

© www.soinside.com 2019 - 2024. All rights reserved.