如何在alamofire中同步上传图片?

时间:2017-06-27 09:06:55

标签: ios swift3 alamofire image-uploading

我使用swift 3和Alamofire 4。我想在for循环中上传6个图像,但是alamofire上传请求是异步运行的。它的作用是先运行循环然后再运行上传。但是我想等到我收到回复然后再上传。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

您应该使用序列DispatchQueue按顺序运行图片上传。串行队列将确保一次只运行一个请求,而下一个请求仅在前一个请求完成执行时开始。

let serialQueue = DispatchQueue(label: "serialQueue")
for image in images {
    serialQueue.async{
       //upload image with Alamofire here
    }
}

答案 1 :(得分:0)

模型类

class MultipartUpdataData: NSObject
{
    var mediaData:Data!
    var mediaUploadKey:String!
    var fileName:String!
    var mimeType:String!
    override init()
    {

    }
    required   init(coder aDecoder: NSCoder) {

        if let mediaData = aDecoder.decodeObject(forKey: "mediaData") as? Data {

            self.mediaData = mediaData
        }
        if let mediaUploadKey = aDecoder.decodeObject(forKey: "mediaUploadKey") as? String {

            self.mediaUploadKey = mediaUploadKey
        }
        if let fileName = aDecoder.decodeObject(forKey: "fileName") as? String {

            self.fileName = fileName
        }
        if let mimeType = aDecoder.decodeObject(forKey: "mimeType") as? String {

            self.mimeType = mimeType
        }
    }
    open func encodeWithCoder(_ aCoder: NSCoder)
    {
        if let mediaData = self.mediaData{
            aCoder.encode(mediaData, forKey: "mediaData")
        }
        if let mediaUploadKey = self.mediaUploadKey {
            aCoder.encode(mediaUploadKey, forKey: "mediaUploadKey")
        }
        if let mimeType = self.mimeType {
            aCoder.encode(mimeType, forKey: "mimeType")
        }
        if let fileName = self.fileName {
            aCoder.encode(fileName, forKey: "fileName")
        }
    }

}

上传图片,首先确保将imageData附加到数组中然后调用此函数如下: -

 var uploadMediaList  = [MultipartUpdataData]()
for loop{
let multiObject  = MultipartUpdataData()
            multiObject.mediaData = self.pngImageData!
            multiObject.mimeType = "image/png"
            multiObject.mediaUploadKey = "profile_pic" //Replace this key with your existing key.
            let profileFilename = self.filename(Prefix: "profile", fileExtension: "png")
            multiObject.fileName = profileFilename
            uploadMediaList.append(multiObject)
}
self.upload(uploadMediaList)

func upload(multipartImages:[MultipartUpdataData]){
        let parameters:[String:String] = ["key":"value"]
        Alamofire.upload(
            multipartFormData: { multipartFormData in


                for mData in multipartImages!{
                    let pngImageData = mData.mediaData
                    let uploadfileNamekey = mData.mediaUploadKey
                    let fileName = mData.fileName!
                    let mimeType = mData.mimeType!
                    multipartFormData.append(pngImageData!, withName: uploadfileNamekey!, fileName: fileName, mimeType: mimeType)

                }
                for (key, value) in parameters {
                    multipartFormData.append(value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: true)!, withName: key)
                }

        },
            to: "\(url)",
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        let json = JSON(data: response.data!)

                    print("SUCSESS")

                    }
                case .failure(let encodingError):
                   print("ERORR")

                }
        }
        )
    }
//MARK:-filename-
    func filename(Prefix:String , fileExtension:String)-> String
    {
        let dateformatter=DateFormatter()
        dateformatter.dateFormat="MddyyHHmmss"
        let dateInStringFormated=dateformatter.string(from: NSDate() as Date )
        return  NSString(format: "%@_%@.%@", Prefix,dateInStringFormated,fileExtension) as String
    }

答案 2 :(得分:0)

您可以使用DispatchGroup课程。

  

DispatchGroup允许工作的聚合同步。

     

您可以使用它们提交多个不同的工作项目并进行跟踪   当它们全部完成时,即使它们可能会运行不同   队列。

     

当直到所有进展都无法取得进展时,此行为会很有帮助   指定的任务已完成。

示例代码:

let dispatchGroup = DispatchGroup()

var i = 0
for element in yourImageArray {
    dispatchGroup.enter()
    i = i+1

    Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
        print("Finished request \(i)")
        dispatchGroup.leave()
    }
}

dispatchGroup.notify(queue: .main) {
    print("Finished all requests.")
}