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

标签 ios swift alamofire image-uploading

我正在通过 alamofire 网络使用 for 循环上传多个图像,但我想在不使用 for 循环的情况下上传多个图像。有没有什么方法或方法可以上传多张图片而无需for循环。

最佳答案

这是我工作中的工作代码,您需要导入一些必需的类并根据您的网络服务参数更改参数。

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

关于ios - 使用 alamofire 上传多个图像,而不使用 swift 中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920356/

相关文章:

arrays - 如何附加到作为 Swift 字典中值的数组

ios - 如何使用 Alamofire (Swift) 获取数组内的嵌套数组

ios - 如何在调用 AlamoFire 的 POST 函数时使用完成处理程序?

Json 解析 Swift 3 Alamofire

ios - 我如何检测由 CATransaction 触发的动画的完成

ios - CloudKit+Core Data 在生产中突然停止同步

swift - 从 firebase 数据库查询数据时的奇怪行为

ios - 从 Visual Studio 2015 构建适用于 iOS 的 Cordova 应用程序时如何解锁钥匙串(keychain)

ios - 在没有操作系统的情况下阅读 Apple 崩溃报告

swift - 为文本字段 swift 4 设置字符数和字符类型限制