2016-06-27 8 views
2

So habe ich ein Bild von einer URL herunterzuladen wie soanzeigen Lade Prozentsatz Bild Download-URL mit schnellen

 let request = NSMutableURLRequest(URL: NSURL(string: "\(self.ip)")!) 
     request.HTTPMethod = "POST" 
     let postString = "userID=\(userID)" 
     request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 

     let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 
     let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue()) 

     let task = session.dataTaskWithRequest(request) { 
      data, response, error in 
        ......... 
     } 

und mein Delegaten Funktionen aussehen

func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { 

    let uploadProgress:Float = Float(totalBytesSent)/Float(totalBytesExpectedToSend) 
    let progressPercent = Int(uploadProgress*100) 
    print(progressPercent) 
} 

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { 
    let downloadProgress:Float = Float(downloadTask.countOfBytesReceived)/Float(downloadTask.countOfBytesExpectedToReceive) 
    print(downloadProgress) 
} 

Der Upload-Fortschritt funktioniert gut für eine andere Funktion, aber beim Herunterladen eines Bildes wird die zweite URLSession-Funktion nicht aufgerufen. Was mache ich falsch?

Antwort

8

NSURLSession hat 5 Arten von Delegierten: NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate und NSURLSessionStreamDelegate. Sie können über sie in der documentation lesen.

Die, die Sie zu kümmern brauchen, sind NSURLSessionDelegate und NSURLSessionDownloadDelegate:

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate { 

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

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    @IBAction func downloadImage(sender : AnyObject) { 
     // A 20MB image from NASA 
     let url = NSURL(string: "http://eoimages.gsfc.nasa.gov/images/imagerecords/78000/78314/VIIRS_3Feb2012_lrg.jpg")! 

     let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
     let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) 

     // Don't specify a completion handler here or the delegate won't be called 
     let task = session.downloadTaskWithURL(url)  
     task.resume() 
    } 

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 
     print("Downloaded \(totalBytesWritten)/\(totalBytesExpectedToWrite) bytes ") 

     dispatch_async(dispatch_get_main_queue()) { 
      self.progressView.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
     } 
    } 

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { 
     // The location is only temporary. You need to read it or copy it to your container before 
     // exiting this function. UIImage(contentsOfFile:) seems to load the image lazily. NSData 
     // does it right away. 
     if let data = NSData(contentsOfURL: location), image = UIImage(data: data) { 
      dispatch_async(dispatch_get_main_queue()) { 
       self.imageView.contentMode = .ScaleAspectFit 
       self.imageView.clipsToBounds = true 
       self.imageView.image = image 
      } 
     } else { 
      fatalError("Cannot load the image") 
     } 

    } 
} 
+0

Dank! Der Beendigungshandler hat verhindert, dass die Funktion –

+0

aufgerufen wurde. Das funktionierte großartig. Vielen Dank! – dinesharjani