Swift programming using Xcode 7.3.
functableView(table:UITableView, cellForRowAtIndexPath:NSIndexPath)->UITableViewCell{
letcell=table.dueReusableCellWithIdentifier("Cell") as? CustomTableViewCell
let url —NSURL = NSURL (string: (fileArray [indexPath.row] as ? US>String)!+ ".jpg")!
let req = NSURLRequest (URL: url)
NSURLConnection.sendAsynchronousRequest(requ,queue:NSOperationQueue.mainQueue()) {(res,data,err)in
let img = UIImage (data:data!)
cell!.thumb.image=img
}
As shown in , the image (cell.thumb.image) is displayed in the cell, but if you scroll fast, the image cannot be read and displayed, and the thumbnail flaps when it stops.
Would it be possible to read images that do not need to be displayed or cancel the display?
swift uitableview
To download the image, create the In the example below, we use the dictionary When a cell exits the screen, the Below is an example code.NSURLConnection.sendAsynchronousRequest()
does not support cancellation processing.NSURLConnection
also has a cancelable API, but NSURLConnection is deprecated from iOS 9, so use a new one, such as NSURLSession
or library.
NSURLSessionDataTask
from NSURLSession
.Keep the NSURLSessionDataTask
so that you can cancel it later if the cell is hidden (off-screen).downloadTasksPerURL
to keep the URL as a key.
Also, we have cells have the URL of the image so that they can identify the NSURLSessionDataTask
to cancel when the cell is hidden.tableView(_:didEndDisplayingCell:forRowAtIndexPath:)
delivery method is called, so cancel the appropriate NSURLSessionDataTask
with the cancel()
method at that time....
var downloadTasksPerURL = NSURLSessionTask()
...
functableView(table:UITableView, cellForRowAtIndexPathindexPath:NSIndexPath) ->UITableViewCell{
...
let imageURL=...
let task = NSURLSession.sharedSession().dataTaskWithRequest (NSURLRRequest (URL: imageURL)) {(data, response, error) ->Void in
iflet error = error {
return
}
dispatch_async(dispatch_get_main_queue()) {
let image=UIImage(data:data!)!
cell!.thumb.image=image
}
}
cell.imageURL=imageURL
downloadTasksPerURL [imageURL] = task
task.resume()
return cell
}
functableView (tableView: UITableView, didEndDisplayingCell: UITableViewCell, forRowAtIndexPath indexPath:NSIndexPath) {
iflet task=downloadTasksPerURL [cell.imageURL] {
task.cancel()
}
}
© 2024 OneMinuteCode. All rights reserved.