Search code examples
iosswiftalamofireswift3

Alamofire method not work after upgrade to 4.0


func downloadProgress(bytesRead: Int64, totalBytesRead: Int64,
    totalBytesExpectedToRead: Int64) {
    let percent = Float(totalBytesRead)/Float(totalBytesExpectedToRead)

    dispatch_async(dispatch_get_main_queue(), {
        self.progress.setProgress(percent,animated:true)   
    })
    print("Progress:\(percent*100)%")
}

func downloadResponse(request: NSURLRequest?, response: NSHTTPURLResponse?,
    data: NSData?, error:NSError?) {
    if let error = error {
        if error.code == NSURLErrorCancelled {
            self.cancelledData = data 
        } else {
            print("Failed to download file: \(response) \(error)")
        }
    } else {
        print("Successfully downloaded file: \(response)")
    }
}

@IBAction func continueBtnClick(sender: AnyObject) {
    if let cancelledData = self.cancelledData {
        self.downloadRequest = Alamofire.download(resumeData: cancelledData,
            destination: destination)

        self.downloadRequest.progress(downloadProgress) 

        self.downloadRequest.response(completionHandler: downloadResponse) 

        self.stopBtn.enabled = true
        self.continueBtn.enabled = false
    }
}

The codes works fine on Alamofire 3.1, but it refuse to work after upgrading to Swift 3.0 and Alamofire 4.0.

The following two line shows error "no such memeber fo progress" and " no such member of response"

  1. self.downloadRequest.progress(downloadProgress)
  2. self.downloadRequest.response(completionHandler: downloadResponse)

How can I solve these two problems?

Thanks.


Solution

  • The functions, which you are referring to have changed with Alamofire 4.0. The reason for the "no members" error is that the function calls have changed. According to the new documentation this is the call that you should (probably) be making:

    Alamofire.download("https://httpbin.org/image/png")
    .downloadProgress { progress in
        print("Download Progress: \(progress.fractionCompleted)")
    }
    .responseData { response in
        if let data = response.result.value {
        }
    }
    

    The new functions according to Xcode (I use Alamofire 4.0 as well but not with .Download):

    downloadRequest.downloadProgress(closure:  Request.ProgressHandler)
    downloadRequest.responseData(completionHandler: (DownloadResponse<Data>) -> Void)
    

    Source: Alamofire documentation for download progress