How to get download progress in AFNetworking 2.0?

前端 未结 4 1468
一整个雨季
一整个雨季 2020-11-29 02:16

I am using AFURLSessionManager to create a new download task:

AFURLSessionManager* manager = ...

NSProgress* p = nil;
NSURLSessionDownloadTask* downloadTask         


        
4条回答
  •  -上瘾入骨i
    2020-11-29 02:50

    Simple solutions for Swift:

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let sessionManager = AFURLSessionManager(sessionConfiguration: sessionConfiguration)
    let request = NSURLRequest(URL: url)
    let sessionDownloadTask = sessionManager.downloadTaskWithRequest(request, progress: nil, destination: { (url, response) -> NSURL in
    
                return destinationPath.URLByAppendingPathComponent(fileName) //this is destinationPath for downloaded file
    
                }, completionHandler: { response, url, error in
    
                    //do sth when it finishes
            })
    

    Now you have 2 options:

    1. Using UIProgressView and setProgressWithDownloadProgressOfTask:

      progressView.setProgressWithDownloadProgressOfTask(sessionDownloadTask, animated: true)
      
    2. Using AFURLSessionManager and setDownloadTaskDidWriteDataBlock:

      sessionManager.setDownloadTaskDidWriteDataBlock { session, sessionDownloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
      
          let progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
              //do sth with current progress
      }
      

    At the end do not forget about:

    sessionDownloadTask.resume()
    

提交回复
热议问题