在异步函数

时间:2018-05-29 06:09:44

标签: ios swift alamofire swift4 alamofireimage

我在Home VC中上传了Alamofire的文件。但是在类函数中上传func。所以我没有得到进展操作。我想我必须写代理方法。

有人会帮助我吗?

我的问题在ViewController !!!

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

在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. !!!
    }

}

1 个答案:

答案 0 :(得分:2)

但是你的问题没有完成,所以假设

Alamofire 会在除多部分请求之外的任何上传请求中返回 UploadRequest 对象

上传请求的属性为进度

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

可用于跟踪上传的进度

修改

您必须将带闭包的数据传递给视图控制器

这是你的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
        }
    }
}

你可以通过

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

    }
}