我正在使用NSURLSession提取数据,但是我不知道下载完成后如何取回数据:

class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionDataDelegate{

@IBOutlet var imageView: UIImageView!
@IBOutlet weak var progress: UIProgressView!

var buffer:NSMutableData = NSMutableData()
var session:NSURLSession?
var dataTask:NSURLSessionDataTask?
let url = NSURL(string:"https://initiate.alphacoders.com/download/wallpaper/566046/images7/jpg/37100/1353" )!
var expectedContentLength = 0
var downloadedImage = UIImage()
var downloadedData = NSData()


override func viewDidLoad() {
    super.viewDidLoad()
    progress.progress = 0.0
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let manqueue = NSOperationQueue.mainQueue()
    session = NSURLSession(configuration: configuration, delegate:self, delegateQueue: manqueue)
    dataTask = session?.dataTaskWithRequest(NSURLRequest(URL: url))
    dataTask?.resume()

    // Do any additional setup after loading the view, typically from a nib.
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

    //here you can get full lenth of your content
    expectedContentLength = Int(response.expectedContentLength)
    print(expectedContentLength)
    completionHandler(NSURLSessionResponseDisposition.Allow)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {

    if progress.progress > 0.99 {

        downloadedImage = UIImage(data: data , scale:  1)!
    }
    buffer.appendData(data)

    print("checking")

    let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength)
    progress.progress =  percentageDownloaded
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    //use buffer here.Download is done
    progress.progress = 1.0// download 100% complete

    imageView.image = downloadedImage
}
}

我试图从func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData中获取数据,但是在didReceiveData中,我的文件尚未完全下载,并且我不知道如何从didCompleteWithError函数中获取数据,这是一种迅速而又新颖的方法,仍然可以在这里找到问题,

如果有人在这里知道我的缺失或应该做什么,那么请告诉我,任何指导都将受到赞赏和帮助。

最佳答案

- URLSession:downloadTask:didFinishDownloadingToURL:

是您缺少的东西。

call 以通知代表下载任务已完成下载。

此方法为您提供临时文件的文件URL(第三个参数)。由于该文件是临时文件,因此您必须先打开文件以进行读取,或者将其移至应用的沙箱容器目录中的永久位置,然后再从此委托方法返回。

查找更多here

编辑1:要检查method之后的进度覆盖:
- URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:

编辑2:好,我现在看到了。进行以下更改,看看是否可行?:
  • 让您的 class 遵循NSURLSessionDownloadDelegate
  • dataTask = session?.dataTaskWithRequest(NSURLRequest(URL: url))更改为dataTask = session?.downloadTaskWithURL(NSURLRequest(URL: url))

  • 那应该使您下载文件。

    08-06 13:08