My problem is when I scroll down my UITableView, it looks too laggy. The images grab from facebook.
My code
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell
let user = users[indexPath.row] as User //2
if let nameLabel = cell.viewWithTag(100) as? UILabel { //3
nameLabel.text = user.name
}
if let dateCreatedLabel = cell.viewWithTag(101) as? UILabel {
dateCreatedLabel.text = user.distance
}
if let profilePictureView = cell.viewWithTag(103) as? UIImageView {
if let url = NSURL(string: "https://graph.facebook.com/\(user.profilePhoto)/picture?type=large") {
if let data = NSData(contentsOfURL: url){
profilePictureView.contentMode = UIViewContentMode.ScaleAspectFit
profilePictureView.image = UIImage(data: data)
}
}
}
return cell
}
Please advice how to make it smooth.
OMG, never do like this not only in scrolling controls, but in general UI also:
data = NSData(contentsOfURL: url)
Thats why you table lags, and you lucky enougth with fast internet. If you connection will be slow, you app will hang, may be forever. ALWAYS do network asyncronously!
Also, when you make you network async, your tableView will still lag here:
UIImage(data: data)
And even here if you have many controls in your cell:
cell.viewWithTag(101)
So, use some library to download images, this is surprisingly not so easy task as it seems to be, you will not do it right yourself according to you experience (as I can see it).
Make separate class for you cell and use IB to connect outlets.
Try AFNetworking, it has category for UIImageView to download images.
I already found the answer. Use Haneke instead NSData.
import Haneke
/* .. */
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) as UITableViewCell
let user = users[indexPath.row] as User //2
if let nameLabel = cell.viewWithTag(100) as? UILabel { //3
nameLabel.text = user.name
}
if let dateCreatedLabel = cell.viewWithTag(101) as? UILabel {
dateCreatedLabel.text = user.distance
}
if let profilePictureView = cell.viewWithTag(103) as? UIImageView {
if let url = NSURL(string: "https://graph.facebook.com/\(user.profilePhoto)/picture?type=large") {
profilePictureView.contentMode = UIViewContentMode.ScaleAspectFit
profilePictureView.hnk_setImageFromURL(url!)
}
}
return cell
}
Related
I have a tableView that contains a UIImageView and if the Image has a URL then the image displays and if not then no Image is displayed. The issue I have is that if there is no Image then a big blank spot occurs in the TableView as if there was an image. Is there a way to reduce the blank spot or hide it (Images below) ? The image is the big UIImageView in the center . This is my code when it comes to the Images
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyFeed", for: indexPath) as! MyFeed
if stream_image_string[indexPath.row].characters.count > 2 {
let strCellImageURL = self.stream_image_string[indexPath.row]
let imgURL: NSURL = NSURL(string: strCellImageURL)!
let request:NSURLRequest = NSURLRequest(url: imgURL as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
DispatchQueue.main.async(execute: { () -> Void in
cell.post_image.image = UIImage(data: data!)
})
});
task.resume()
} else {
cell.post_image!.isHidden = true
cell.post_image!.image = nil
}
return cell
}
Essentially if the String coming back has 2 or more characters then it's a valid URL and the image is downloaded; the part that I am focused on is the else statement and this code
else {
cell.post_image!.isHidden = true
cell.post_image!.image = nil
}
So obviously if it goes in the else statement then there is no image and I set the Image to null or nil then I try to hide the extra white space by setting the Image to hidden however that does not work . Any idea on how I can hide the white space ? I have also been reading this question but it does not work iOS swift imageView cannot be hidden in TableViewCell
Give outlet of image's width and if there is no image then set constant of that outlet to "0".
e.g.
if(!image)
{
widthOfImage.constant = 0
}
I experienced the same problem myself. You need to create 2 cells for this. Like this:
override func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (stream_image_string[indexPath.row] == "")
{
let cell = tableView.dequeueReusableCell (withIdentifier: "noImageMyFeed", for: indexPath) as! noImageMyFeed
return cell
}
else
{
let cell = tableView.dequeueReusableCell (withIdentifier: "MyFeed", for: indexPath) as! MyFeed
return cell
}
}
this video will help you in detail : https://www.youtube.com/watch?v=FAxtWtqeMIM
adapt the video to its own content, create a cell from scratch by simply deleting the image part
I'm trying to show images from XML enclosure to tableViewCell image. Images are show but not in sequence, due to dequeueReusableCellWithIdentifier because when i scroll tableViewCell up and down it change images and not show in sequence according to array index. I've tried different ways but did't get success'
Can anyone please tell me how can show images in sequence, or is there any way that first download all images and then show in cell image??
Or any other quick or easy method instead using dispatch_async.
Thanks
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : ImageCell2 = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ImageCell2
cell.titleLabel.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
downloadFileFromURL(NSURL(string: self.posts.objectAtIndex(indexPath.row).valueForKey("enclosure") as! String)!, completionHandler:{(img) in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.sideImageView.image = img
})
})
return cell
}
UPDATE
Now i tried this
let picURL = self.posts.objectAtIndex(indexPath.row).valueForKey("enclosure") as! String
let url = NSURL(string: picURL)
let data = NSData(contentsOfURL: url!)
cell.sideImageView?.image = UIImage(data: data!)
It show images in sequence but make scrolling hard?
Update2
Now i've tried this
var check = true
var imageArrayNsData : [NSData] = []
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : ImageCell2 = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ImageCell2
cell.titleLabel.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
if check == true{
var indeX = 0
for i in posts.valueForKey("enclosure") as! [NSString]{
let picURL = self.posts.objectAtIndex(indeX).valueForKey("enclosure") as! String
let url = NSURL(string: picURL)
let data = NSData(contentsOfURL: url!)
print("download")
imageArrayNsData.append(data!)
indeX++
print(indeX)
}
check = false
}
if check == false{
cell.sideImageView.image = UIImage(data: imageArrayNsData[indexPath.row])
}
return cell
}
This method only download images one time. And after downloading images it appends in array and next time it show images from array without downloading again. But this method is little bit hard for scrolling. Any one have idea why?
The problem is that the cell object may have been already reused by the time you set the image. You need to add a check to make sure the cell still represents the content you want. That could be as simple as:
if tableView.indexPathForCell(cell) == indexPath {
cell.sideImageView.image = img
}
But might need to be more complex if the index path for a specific item might change in that time (for example, if the user can insert/delete rows).
You could also use a library like AlamofireImage which handles this work (in a different way) for you. With AlamofireImage, your code would look like:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : ImageCell2 = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ImageCell2
cell.titleLabel.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
let URL = NSURL(string: self.posts.objectAtIndex(indexPath.row).valueForKey("enclosure") as! String)!
cell.sideImageView.af_setImageWithURL(URL)
return cell
}
To download asynchronously images and set to UIImageView of your UITableViewCell, you can add an extension to your UIImageView.
extension UIImageView {
func downloadImageFrom(link link:String, contentMode: UIViewContentMode) {
//in my methods, I have a cache to avoid re-downloading my images. Images in cache are identified by its URL
if let _imageData = ImageCache.shareCache.getImageData(link) {
self.image = UIImage(data: _imageData)
return
}
//else, download image
NSURLSession.sharedSession().dataTaskWithURL( NSURL(string:link)!, completionHandler: {
(data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.contentMode = contentMode
if let data = data {
ImageCache.shareCache.cacheImageData(data, imageId: link)
self.image = UIImage(data: data)
}
}
}).resume()
}
}
then, from your call-back cellforrow,
let cell : ImageCell2 = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ImageCell2
cell.titleLabel.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
cell.imageView.downloadImageFrom(yourImageUrl)
return cell
I'm trying to load images extracted from the web URL into the image view of each cell.
However, when i scroll the table the screen will freeze as I believe it is attempting to grab the images for each cell 1 by 1.
Is there a way i can make it asynchronous? The resources available out there currently is outdated or incompatible(running obj c) as I'm running on Swift 2
The relevant code I'm using within the table view controller is below :
override func tableView(newsFeedTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let blogPost: BlogPost = blogPosts[indexPath.row]
cell.textLabel?.text = blogPost.postTitle
let unformattedDate = blogPost.postDate
//FORMATTING: Splitting of raw data into arrays based on delimiter '+" to print only useful information
let postDateArr = unformattedDate.characters.split{$0 == "+"}.map(String.init)
cell.detailTextLabel?.text = postDateArr[0]
let url = NSURL(string: blogPost.postImageUrl)
let data = NSData(contentsOfURL: url!)
cell.imageView!.image = UIImage(data: data!)//WHY SO SLOW!?
print(blogPost.postImageUrl)
return cell
}
Try this
var image: UIImage
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {() -> Void in
// Background thread stuff.
let url = NSURL(string: blogPost.postImageUrl)
let data = NSData(contentsOfURL: url!)
image = UIImage(data:data)
dispatch_async(dispatch_get_main_queue(), {() -> Void in
// Main thread stuff.
cell.imageView.image = image
})
})
Lets clean your code a bit. First of all, you are trying to declear ALL your cells in your viewController. That means your app is not trying to load every image one byt one, but more like everything all together.
You need to create a separate file called PostCell what is going to be a type of UITableViewCell.
Then you need to go to your prototype cell and connect those view elements to that PostCell just like you would add those to any other ViewController.
Now, here is new code to your cellForRowAtIndexPath function:
override func tableView(newsFeedTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let blogPost = blogPosts[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? PostCell {
cell.configureCell(blogPost)
return cell
}
return UITableViewCell() // You need to do this because of if let
}
And declear this on that PostCell:
func configureCell(post: BlogPost) {
this.textLabel.text = post.postTitle
let postDateArr = unformattedDate.characters.split{$0 == "+"}.map(String.init)
this.detailTextLabel.text = postDateArr[0]
// I would add few if let declarations here too, but if you are sure all these forced ! variables do exciest, then its ok
let url = NSURL(string: blogPost.postImageUrl)
let data = NSData(contentsOfURL: url!)
this.imageView.image = UIImage(data: data!)
}
Or something along those lines. When you connect those elements to your cell, you will get proper variable names for those.
That SHOULD help. There are plenty of tutorials how to make a custom tableviewcell. Some of them advice to put all the declarations inside that cellForRowAtIndexPath, but I have found that it get's problematic very fast.
So...my advice in a nutscell...create a custom tableviewcell.
Hope this helps! :)
To load the image on every cell use SDWebImage third party library. You can add it using pods as put pod 'SDWebImage' It provides various methods to load the image with caching or without caching asynchronously. With caching you don't really need to worry about loading image data every time cell appears on the screen. Try this
override func tableView(newsFeedTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? PostCell {
--reset your cell here--
// cell.imageView.image = nil
}
cell.imageView.sd_setImageWithURL(YOUR_URL, placeholderImage: UIImage(named: "")) {
(UIImage img, NSError err, SDImageCacheType cacheType, NSURL imgUrl) -> Void in
// Do awesome things
}
-- configure your cell here --
}
I am loading a tableview of images that are being fetched from a public CloudKit database as CKAssets. However, the images are loading out of order about two seconds until the correct image is loaded into the UIImageView of a custom UITableview cell. I know that the issue is that since the cell is reusable the image is still downloaded from CloudKit and displayed in any visible cell while a user is scrolling through the TableView before the correct image is shown in the image view. I am wondering if there is a fix to this in swift so that the image downloaded is only for that of a visible cell and not any previous cells.
Here is the code for cellForRowAtIndexPath:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PostsTableViewCell
cell.userInteractionEnabled = false
photoRecord = sharedRecords.fetchedRecords[indexPath.row]
cell.photoTitle.text = photoRecord.objectForKey("photoTitle") as? String
cell.photoImage.backgroundColor = UIColor.blackColor()
cell.photoImage.image = UIImage(named: "stock_image.png")
if let imageFileURL = imageCache.objectForKey(self.photoRecord.recordID) as? NSURL {
cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageFileURL)!)
cell.userInteractionEnabled = true
print("Image Cached: \(indexPath.row)")
} else {
let container = CKContainer.defaultContainer()
let publicDatabase = container.publicCloudDatabase
let fetchRecordsImageOperation = CKFetchRecordsOperation(recordIDs:[self.photoRecord.recordID])
fetchRecordsImageOperation.desiredKeys = ["photoImage"]
fetchRecordsImageOperation.queuePriority = .VeryHigh
fetchRecordsImageOperation.perRecordCompletionBlock = {(record:CKRecord?, recordID:CKRecordID?, error:NSError?) -> Void in
if let imageRecord = record {
NSOperationQueue.mainQueue().addOperationWithBlock() {
if let imageAsset = imageRecord.objectForKey("photoImage") as? CKAsset{
cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!)
self.imageCache.setObject(imageAsset.fileURL, forKey:self.photoRecord.recordID)
cell.userInteractionEnabled = true
}
}
}
}
publicDatabase.addOperation(fetchRecordsImageOperation)
}
return cell
}
Thanks in advance!
There is latency between when your table view appears and when fetchRecordsImageOperation.perRecordCompletionBlock is called. Within that time the user may scroll the table view causing the table view cell to dequeue and requeue with a different indexPath and different data associated with it, if you do not check that the cell's index path is the same as when you constructed fetchRecordsImageOperation.perRecordCompletionBlock, this line: cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!) will cause the image to be placed in the cell that is already displaying different data. You can modify your completion block like so to avoid this.
if let imageRecord = record {
NSOperationQueue.mainQueue().addOperationWithBlock() {
if let imageAsset = imageRecord.objectForKey("photoImage") as? CKAsset{
if indexPath == tableView.indexPathForCell(cell){
cell.photoImage.image = UIImage(data: NSData(contentsOfURL: imageAsset.fileURL)!)
}
self.imageCache.setObject(imageAsset.fileURL, forKey:self.photoRecord.recordID)
cell.userInteractionEnabled = true
}
}
}
You find the answer in here I believe, I bias of course cause I wrote it.
How to determine when all images have been downloaded from a set in Swift?
You should setup an image to display while its loading an image and show that so that the user understands what is happening?
I have UITableView with images in each cell and I want my scrolling be smooth. So I read some post on stackerflow and now I am loading my images in background thread:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: BuildingStatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuildingStatusCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
var node = nodesArray[indexPath.row] as! NSMutableDictionary
if !checkIfImagesLoaded(node[Api.pictures] as! NSMutableArray) {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
cell.indicator.hidesWhenStopped = true
cell.indicator.startAnimating()
dbHelper.getBuildingStatusNode(node, callback: self)
} else {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
var image = WorkWithImage.loadImageFromSD((node[Api.pictures] as! NSMutableArray)[0]["image"] as! String)! // Bad
dispatch_async(dispatch_get_main_queue()) {
cell.imgView.image = image
cell.indicator.stopAnimating()
}
}
}
return cell
}
dbHelper.getBuildingStatusNode(node, callback: self) method executes in background thread also. But for some reasons when I scroll I still get some delay. I read that it is good to fill my cell with data in tableView:willDisplayCell method instead tableView:cellForRowAtIndexPath and I should return cell as faster as I can in tableView:cellForRowAtIndexPath method. The question is should I now use the code like this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: BuildingStatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuildingStatusCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
var cell: BuildingStatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuildingStatusCell
var node = nodesArray[indexPath.row] as! NSMutableDictionary
if !checkIfImagesLoaded(node[Api.pictures] as! NSMutableArray) {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
cell.indicator.hidesWhenStopped = true
cell.indicator.startAnimating()
dbHelper.getBuildingStatusNode(node, callback: self)
} else {
cell.id = node[Api.buildingStatusId] as! Int
cell.date.text = node[Api.date] as? String
cell.count.text = String((node[Api.pictures] as! NSMutableArray).count)
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
var image = WorkWithImage.loadImageFromSD((node[Api.pictures] as! NSMutableArray)[0]["image"] as! String)!
dispatch_async(dispatch_get_main_queue()) {
cell.imgView.image = image
cell.indicator.stopAnimating()
}
}
}
}
And what else I can do to make my scrolling more smooth? BCS I still have lags even when I use willDisplayCell method.
P.S. Image size in my UITableViewCells is fixed.
Try the following
Try removing any shadows.
Make the cell and its subviews opaque. Don't use alpha/transparency.
Try decoding the images on a background thread :
Decode images in background thread?
First of all it is better to subclass UITableViewCell and just pass your Api object to cell and make this mapping inside cell.
Also it is better to use some library like: AFNetworking's extension or AsyncImageView - it is possible to use in Swift.
Try to remove any border rounding, shadow, transparencies - they can cause delays. In this case you need rasterization:
Related question:
Sluggish scrolling experience when using QuartzCore to round corners on UIImageView's within a UITableViewCell
When you load image from URL it takes time to download image and that cause block in scrolling UITableView.
You are doing so much work simply do
Use this class SDWebImage
and in your bridging header file :
#import "UIImageView+WebCache.h"
Here is a code example that should work :
let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType!, imageURL: NSURL!) -> Void in
println(self)
}
let url = NSURL(string: node[Api.pictures] as! NSMutableArray)[0]["image"] as! String)
cell.imgView.sd_setImageWithURL(url, completed: block)