完成NSURLSession后获取NSData

时间:2016-02-28 14:12:33

标签: ios nsurlsession

我使用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函数获取数据,我是新的快速而且仍然在这里搞清楚事情,

如果有人在这里知道我错过了什么或者我该怎么办,那么请告诉我,任何指导都会非常感激和乐于助人。

1 个答案:

答案 0 :(得分:1)

- URLSession:downloadTask:didFinishDownloadingToURL:

是你缺少的东西。

致电通知代表下载任务已下载完毕。

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

查找更多here

编辑1:检查method后的进度覆盖:

- URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:

编辑2:好的,我现在看到了。进行以下更改,看看它是否有效?:

  1. 让您的班级符合NSURLSessionDownloadDelegate
  2. dataTask = session?.dataTaskWithRequest(NSURLRequest(URL: url))更改为dataTask = session?.downloadTaskWithURL(NSURLRequest(URL: url))
  3. 这应该让你下载文件。