Я выборки данных с использованием NSURLSession
, но я не знаю, как получить данные обратно после завершения загрузки мой код:Получить NSData после завершения 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
функции, новичок в быстром и все еще здесь,
Если кто-то знает здесь, что мне не хватает или что должен ли я это сделать, пожалуйста, скажите мне, что любое руководство будет так оценено и полезно.
hey @vivekMolkar спасибо за ответного человека, я попытался найти этот метод, но нет ничего как 'didFinishDownloadingToURL' в классе NSURlSession? Вы имели в виду 'URLSessionDidFinishEventsForBackgroundURLSession' ??? –
странно, должно быть, там. см. здесь [link] (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW14). его из яблочных документов. также плз проверить, если вы что-то упустили. –
эй, я понял, что была опечатка моей плохой –