Search code examples
iosswiftalamofireswift4alamofireimage

Get Progress and Error operations with the same time on Async functions


I upload a file with Alamofire in Home VC. But upload func in the class function. So I didnt get the progress operations. I guess I have to write delegate Method.

Anybody will help me?

My Question is in ViewController !!!

In SendPhoto.class

class SendPhoto {


    func send() {
        Alamofire.upload(
        multipartFormData: { multipartFormData in
            ...
    },
        to: "",
        headers:headers,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.uploadProgress {progress in
                    print(progress.fractionCompleted)

                }
                upload.responseJSON { response in

                }
            case .failure(let encodingError):
                print("File Upload Error")
                print(encodingError)
            }
    })
}}

In ViewController

class HomepageVC: UIViewController .. {

    override func viewDidLoad() {
        super.viewDidLoad()
    }


    @IBAction func sendAction(_ sender: Any) {

        SendPhoto().send()

        // I want to keep this function progress and print to a label or etc. !!!
    }

}

Solution

  • However your question is not completed so with assumption

    Alamofire returns the UploadRequest object on any upload request except multipart request

    And upload request has property progress

    /// The progress of fetching the response data from the server for the request.
    open var progress: Progress { return dataDelegate.progress }
    

    which can be used to track the uploaded progress

    EDIT

    You have to pass data with closure to your view controller

    Here is your methdo

    private func uploadAnyThing  (progress:@escaping ((Progress) -> Void) , completed:@escaping ((_ success:Bool,_ error:Error?) -> Void)) {
        Alamofire.upload(multipartFormData: { (data) in
    
        }, to: "test.com") { (result) in
            switch (result) {
            case .success(let request, _, _):
                request.uploadProgress(closure: { (prog) in
                    progress(prog)
                })
    
                request.responseJSON(completionHandler: { (res) in
                    completed(true,nil)
    
                })
    
            case .failure(let error) :
                completed(false,error)
                break
            }
        }
    }
    

    And you can get it by

    func test () {
        uploadAnyThing(progress: { (progres) in
            print(progres.fractionCompleted)
        }) { (success, error) in
    
        }
    }