How to do image upload in alamofire Synchronously ?

alamofire upload
swift alamofire get request
alamofire get request swift 4
alamofire wait for response
is alamofire asynchronous
alamofire cache
alamofire multipart form data swift 4
alamofire session manager

Im using swift 3 and Alamofire 4 . I want to upload 6 images inside a for loop but alamofire upload request run asynchronously. What it does is it runs for loop first and then the upload. But i want to wait until i get a response and then upload next. How can i do this?

You should use a serial DispatchQueue to run your image uploads sequentially. The serial queue will ensure that only one request will be run at a time and the next one only starts when the previous one finished execution.

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

How to upload image synchronously · Issue #2143 · Alamofire , How to upload image synchronously with parameter. By doing so, you'll be more likely to quickly solve your problem, and you'll allow anyone  Next, we’ll need to get a reference to the image view from the Main.storyboard in our code. Select the view controller from the Main.storyboard and click on the double circle symbol in the top right corner of Xcode. This should open ViewController.swift in a second window to the right. Now,

Model Class

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

}

Upload Image, First make sure to append imageData into array then call this function like below:-

 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
    }

Dalodd/Alamofire-Synchronous: Synchronous requests for , Synchronous requests for Alamofire. Contribute to Dalodd/Alamofire-​Synchronous development by creating an account on GitHub. Swift 3 Alamofire multipart upload. Ask Question If you don't need to have your request object synchronously the other answer with How to upload Image in

You can use DispatchGroup class.

DispatchGroup allows for aggregate synchronization of work.

You can use them to submit multiple different work items and track when they all complete, even though they might run on different queues.

This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.

Sample code:

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.")
}

Alamofire:Elegant HTTP Networking in Swift, Networking in Alamofire is done asynchronously. These values can be passed as the first argument of the Alamofire.request method: Alamofire.upload(. AlamofireImage - An image library including image response serializers, UIImage​  I am trying to do a synchronous request using Alamofire. I have looked on Stackoverflow and found this question: making an asynchronous alamofire request synchronous . I saw that the accepted answer uses completion to make Alamofire request synchronous but I cannot make it to work.

Upload image to server using URLSessionUploadTask, What is happening under the hood of Alamofire / AFNetworking library? Some answer from Stack Overflow might contain weird looking string like  In Swift 2.2 NSURL.path returns the entire URL. In Swift 3 however URL.path returns only the file path and not the entire URL. Since all Alamofire functions take an URL as argument this is mostly not a problem, but for this scenario it is, since it takes a string.

Alamofire get request swift 4 with parameters, Since this HTTP request is executed asynchronously (to avoid blocking up Swift Alamofire: How to get the HTTP response status code (6) Best way to In this example, i have a case upload image from picker with parameters access token. RoundedCornersFilter - Rounds the corners of an image to the specified radius. CircleFilter - Rounds the corners of an image into a circle. BlurFilter - Blurs an image using a CIGaussianBlur filter with the specified blur radius.

Alamofire 4, It is optional, so you can pass nil if you don't have an image to pass. parameters: [​String : Any] — an argument where you need to pass your additional key value  What did you do? I'm trying to upload an image which is converted to base64 string and some other parameters such as username and password. however when I try to append the image and send it to server, I get response that I'm not sending all parameters! What did you expect to happen? I have problem uploading base64 string with multipart form data.

Comments
  • FYI Alamofire runs asynchronously for a reason. It's almost always a bad design decision to try to run uploads (or any network request really) synchronously.
  • If you're worried that the network connection is going to be too weak to handle multiple uploads at once (which you should be), then there are other ways (look into alamo fire SessionManager and URLSessionConfiguration which has a httpMaximumConnectionsPerHost property.