Alamofire POST request with progress

前端 未结 3 899
臣服心动
臣服心动 2021-01-02 19:06

I\'m using Alamofire to do a POST request. As this POST request can take a while and I want to keep track of the progress and display it as a ProgressView.

A         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 19:18

    What you can do instead is first use the ParameterEncoding enum to generate the HTTPBody data. Then you can pull that data out and pass it off to the Alamofire upload method. Here's a modified version of your same function that compiles in a playground and instead uses the upload function.

    struct ApiLink {
        static let create_post = "/my/path/for/create/post"
    }
    
    let parameters: [String: AnyObject] = ["key": "value"] // Make sure this has your image as well
    
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: ApiLink.create_post)!)
    mutableURLRequest.HTTPMethod = Method.POST.rawValue
    
    let encodedURLRequest = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
    let data = encodedURLRequest.HTTPBody!
    
    let progressView = UIProgressView()
    
    Alamofire.upload(mutableURLRequest, data)
             .progress { _, totalBytesRead, totalBytesExpectedToRead in
                 println("ENTER .PROGRESSS")
                 println("\(totalBytesRead) of \(totalBytesExpectedToRead)")
                 progressView.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)
             }
             .responseJSON { _, _, mydata, _ in
                 println(mydata)
             }
    

    This will certainly have progress updates as @mattt originally mentioned in his comment above.

提交回复
热议问题