2
我是IOS開發的新手。你能幫我說說如何使用NSURLSession和didReciveData方法下載圖片嗎?我需要一個進度查看上傳圖片的進度。創建NSUrlSession後,我卡住了。請幫忙。Swift IOS:如何使用NSURLSession和didReciveData下載圖像?
class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate {
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var downloadButton: UIButton!
@IBAction func downloadImage(sender: UIButton) {
let urlString = "https://img-fotki.yandex.ru/get/6111/8955119.3/0_7e1f6_a73b98a0_orig"
let url = NSURL(string: urlString)
var configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session: NSURLSession = NSURLSession(configuration: self.configuration)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
print("didReceiveData")
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
print("didReceiveRes")
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
let alert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(alertAction)
presentViewController(alert, animated: true, completion: nil)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print("didReceiveSendData64")
var uploadProgress: Float = Float(totalBytesSent)/Float(totalBytesExpectedToSend)
progressView.progress = uploadProgress
}
}
惠康,如果你滿意的答案,那麼請不要忘了投票和接受的答案。 –
好的,但我不能投票,因爲我的聲望還不到15。 –
好吧,我明白了。謝謝你編碼愉快。 –