Swift: UICollectionView images loading - ios

I have a problem. My UICollectionView's scroll is too laggy because of the size of the images that are in cells. Image's resizing function changes almost nothing. And I have no ability to make a small copies of the images, because of the images' number.
So what should I do if I need to make a quick images loading just like in native Album app? I heard about "lazy loading", but I can't find any tutorial in Swift about it.
Here is my cellForItemAtIndexPath:
let cell : MyCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! MyCollectionViewCell
let painting = objs[indexPath.row]
let name = (painting.valueForKey("imageName") as? String)!
let path = NSBundle.mainBundle().bundlePath.stringByAppendingString("/\(name)") as NSString
cell.imageView.image = UIImage(contentsOfFile: path as String)
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
return cell
I would be glad if you help me to solve this problem!
PS The app doesn't load it from the WEB. All images are in the app on the device.
UPDATE
Finally, I implemented SDWebImage. This is the best solution I found.
Here is my cellForRowAtIndexPath:
let cell : MyCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! MyCollectionViewCell
let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType, imageURL: NSURL!) -> Void in
// println(self)
}
let path = NSBundle.mainBundle().bundlePath.stringByAppendingString("/\(images[indexPath.row])") as NSString
let url = NSURL.fileURLWithPath(path as String)
println(url)
cell.imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "placeholder"), completed: block)
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
return cell

It is because you are loading image in main thread, better do it on background thread, to make it more smooth better decode image on background thread as well. it you will set image directly it will decode when you will set image to imageView, so better first decode it and then set it to imageView.image
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
var image = UIImage(contentsOfFile: path as String)
UIGraphicsBeginImageContextWithOptions(image!.size, true, 0);
image?.drawAtPoint(CGPointZero)
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.imageView.image = image
})

Why don't you use:
let name = (painting.valueForKey("imageName") as? String)!
cell.imageView.image = UIImage(named: name)
instead of using NSBundleas loading image with name method caches the image

Related

Swift Async Call in UITableView

What is the best way to async call to load a UIImage to a textView as a NSTextAttachment in a tableView? So far this is working very badly.
I am using a URL string to load a single image inside multiple tableView cells.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
//Transform Data From ^ to load at the bottom
tableView.transform = CGAffineTransform (scaleX: 1,y: -1);
cell?.contentView.transform = CGAffineTransform (scaleX: 1,y: -1);
cell?.accessoryView?.transform = CGAffineTransform (scaleX: 1,y: -1);
let username = cell?.viewWithTag(1) as! UITextView
username.text = messageArray[indexPath.row].username
let message = cell?.viewWithTag(2) as! UITextView
//message.text = messageArray[indexPath.row].message // delete later
var test = messageArray[indexPath.row].uploadedPhotoUrl
print(test ?? String.self)
if(test != ""){
// create an NSMutableAttributedString that we'll append everything to
let fullString = NSMutableAttributedString(string: "")
// create our NSTextAttachment
let image1Attachment = NSTextAttachment()
URLSession.shared.dataTask(with: NSURL(string: messageArray[indexPath.row].uploadedPhotoUrl)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? String())
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
image1Attachment.image = image
//calculate new size. (-20 because I want to have a litle space on the right of picture)
let newImageWidth = (message.bounds.size.width - 20 )
//resize this
image1Attachment.bounds = CGRect.init(x: 0, y: 0, width: newImageWidth, height: 200)
// wrap the attachment in its own attributed string so we can append it
let image1String = NSAttributedString(attachment: image1Attachment)
// add the NSTextAttachment wrapper to our full string, then add some more text.
fullString.append(image1String)
fullString.append(NSAttributedString(string: message.text))
// draw the result in a label
message.attributedText = fullString
//message.textStorage.insert(image1String, at: message.selectedRange.location)
message.textColor = .white
test = ""
})
}).resume()
}else {
message.text = messageArray[indexPath.row].message
}
let timeStamp = cell?.viewWithTag(3) as! UILabel
timeStamp.text = messageArray[indexPath.row].timeStamp
let imageView = cell?.viewWithTag(4) as! UIImageView
imageView.image = nil
let urlString = messageArray[indexPath.row].photoUrl
imageView.layer.cornerRadius = 10
imageView.clipsToBounds = true
//Load profile image(on cell) with URL & Alamofire Library
let downloadURL = NSURL(string: urlString!)
imageView.af_setImage(withURL: downloadURL! as URL)
return cell!
}
Images are still lagging when index is scrolling(appearing and disappearing) and are also not loading completely
You are loading an image at a time while the tableviewcell is scrolling. There is some time to call the service and then wait for the response to be returned, thus affecting the scrolling although it is on another thread.
You can try calling the images in batches of maybe 10 or 20 at a time.
TL/DR:
Learn to write better code.
For starters, there's no way tableView(:cellForRowAt:) can accomplish all that work in under 16 milliseconds. I think you should reconsider your app structure and architecture for starters. It would serve your app better to abstract the networking calls to an API that can run on a background thread(s).
One way would be to abstract away a lot of the implementation to anOperationQueue Ray Wenderlich has a couple tutorials on how this works. This particular one was written for Swift 1.2, however the principles for Operation are there.

Custom UItableViewCell not loading Image? Swift 4

I'm new at Xcode and swift and ran into this bug. I've searched around a bit and could not find anything on this topic. I have an extension for UIImage that allows me to cache images to the phone here :
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView{
func loadImageUsingCacheWithUrlString(urlString : String)
{
self.image = nil;
// check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage;
return
}
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
//download hit an error
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!){
imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
self.image = downloadedImage
}
}
}).resume()
}
}
It is not loading the image into a table views image view:( Ignore random text )
Table view not loading image
Here is also the UItableView from the main.storyboard:
Updated main.storyboard screen shot
Here is my cellForRowAt: indexPath method where the image is suppose to be loaded:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)
let message = messages[indexPath.item]
if message.toId == user?.toId{
cell.messageBackground.backgroundColor = red
cell.messageLabel.textColor = UIColor.white
}
else{
cell.messageBackground.backgroundColor = gray
cell.messageLabel.textColor = UIColor.black
}
cell.messageLabel.text = message.text
if let imageUrl = message.imageUrl{
print(imageUrl)
cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)
cell.messageImage.isHidden = false;
cell.messageLabel.isHidden = true
//cell.messageBackground.isHidden = true;
}
else
{
cell.messageImage.isHidden = true;
cell.messageLabel.isHidden = false
cell.messageBackground.isHidden = false;
}
return cell;
}
Expected Result:
Images load into cells
Observed Result
Images dont load into the cells :(
these lines of code :
if let imageUrl = message.imageUrl{
print(imageUrl)
cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)
Actually print a valid URL string for an image on my firebase database, which is confusing because It is not loading the image.
Important
I use the loadImageUsingCacheWithUrlString method in other parts of my project and it works fine so I don't think its the method.... whats going on?? thank you so much if you can solve this you are an amazing coder!!
I can put an image in the main.storyboard and it works... so I dont know what could be going wrong... :(
screen shot of updated main.storyboard
Image seems to be fine in Extension :
code with breakpoint and console showing
Not sure If the image Is being covered Up in Capture View Hierarchy :
View Hierarchy
In your storyboard, the imageView messageImage is a subview of the view messageBackground. In your if-statement in cellForRow method, you are setting the messageBackground to be hidden
if let imageUrl = message.imageUrl{
print(imageUrl)
cell.messageImage.loadImageUsingCacheWithUrlString(urlString: imageUrl)
cell.messageImage.isHidden = false;
cell.messageLabel.isHidden = true
cell.messageBackground.isHidden = true; //THIS IS THE CULPRIT
}
Since messageBackground is hidden, it's subviews are hidden as well. Might need to rethink your business logic here.

Read image from cache for app ios with swift

I'm currently reading images from my firebase storage - which works fine.
I have set up a caching to read images from the cache when it has been read from the storage:
// Storage.imageCache.object(forKey: post.imageUrl as NSString)
static func getImage(with url: String, completionHandler: #escaping (UIImage) -> ())
{
if let image = imageCache.object(forKey: url as NSString)
{
print("CACHE: Unable to read image from CACHE ")
completionHandler(image)
}
else
{
let ref = FIRStorage.storage().reference(forURL: url)
ref.data(withMaxSize: 2 * 1024 * 1024)
{
(data, error) in
if let error = error
{
print("STORAGE: Unable to read image from storage \(error)")
}
else if let data = data
{
print("STORAGE: Image read from storage")
if let image = UIImage(data: data)
{
// Caches the image
Storage.imageCache.setObject(image, forKey: url as NSString)
completionHandler(image)
}
}
}
}
}
}
But its not working. It seems to not work at all as well, I don't have the message ' print("CACHE: Unable to read image from CACHE ")
' being displayed on my console but the print ' print("STORAGE: Image read from storage")
'
Do you know how this can be achieved by any chance please?
Thanks a lot for your time!
---EDIT --
I call the image in table cell view from firebase storage then as:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.feedTableView.dequeueReusableCell(withIdentifier: "MessageCell")! as UITableViewCell
let imageView = cell.viewWithTag(1) as! UIImageView
let titleLabel = cell.viewWithTag(2) as! UILabel
let linkLabel = cell.viewWithTag(3) as! UILabel
titleLabel.text = posts[indexPath.row].title
titleLabel.numberOfLines = 0
linkLabel.text = posts[indexPath.row].link
linkLabel.numberOfLines = 0
Storage.getImage(with: posts[indexPath.row].imageUrl){
postPic in
imageView.image = postPic
}
return cell
}
You can realize caching images with Kingfisher for example. And works better. link
How to use: Add link to your image from storage to database item node. Like this:
Then just use it to present and cache image.
Example:
let imageView = UIImageView(frame: frame) // init with frame for example
imageView.kf.setImage(with: <urlForYourImageFromFireBase>) //Using kf for caching images
Hope it helps

swift downloading url and populating uiimageview

I'm having difficulty getting each image of my tableviewcell to show the thumbnail of my blog. the link is valid as i had it print to screen to make sure it works here is the block of code causing my brain aneurysm
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let blogPost: BlogPost = blogPosts[indexPath.row]
//cell.textLabel?.text = blogPost.postTitle
postImageLink = blogPost.postImageLink
cell.textLabel?.text = blogPost.postImageLink
if postImageLink != "" && cell.imageView?.image != nil {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
cell.imageView?.image = UIImage(data: NSData(contentsOfURL: NSURL(string:self.postImageLink)!)!)
}
} else {
cell.imageView?.image = UIImage(named: "IMG_0079")
}
return cell
}
i set the text label to postimagelink only to ensure it was parsing the correct code for future usage.
To be clear the problem is the thumbnails of my blog won't load. Only the preset image incase a thumbnail isn't present..postImageLink is a unique url for each thumbnail that I parsed.
(yeah i know i can write a parser but can't solve this problem =(..)
any help is appreciated before I throw my laptop off the roof thanks!
here is image
-rookieprogrammer
try to make two blocks instead, to retrieve and set the image
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// retrieve image from url
let image = UIImage(data: NSData(contentsOfURL: NSURL(string:self.postImageLink)!)!)
dispatch_async(dispatch_get_main_queue(), { Void in
// set image in main thread
cell.imageView?.image = image
})
}
can read more here
Your code is working. It's just that should be doing it in the main_queue, UI main thread, to edit any UI objects.
dispatch_async(dispatch_get_main_queue()) {
() -> Void in
// retrieve image from url
let image = UIImage(data: NSData(contentsOfURL:NSURL(string:self.postImageLink)!)!)
cell.imageView?.image = image
}

Swift - Adding image to tableview cell from asset library

I am trying to add an image to a tableview cell but not having much luck getting it to display.
The image is being loaded from the file system (I println() the result) as a UIImage but I cannot seem to get it into the cell. Placing a println() after the closure shows me that the images are all loaded after the cell has been returned.
Here is my code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let note = notes[indexPath.row]
let nsURL = NSURL(string: note.valueForKey("url") as! String)!
var loadError: NSError?
var image: UIImage?
assetsLibrary!.assetForURL(nsURL, resultBlock: { (asset) -> Void in
if let ast = asset {
let iref = ast.defaultRepresentation().fullResolutionImage().takeUnretainedValue()
image = UIImage(CGImage: iref)
println("The loaded image: \(image)")
}
}, failureBlock: {(error) -> Void in
loadError = error
})
cell.textLabel!.text = note.valueForKey("title") as? String
cell.imageView!.image = image
return cell
}
When I replace the closure with the following to load a image from the project itself it shows in the table. This leads me to believe it not due to an issue with the way the story board is set up.
UIImage(named: transportItems[indexPath.row])
Any help would be much appreciated.
It doesn't work that way. cellForRowAtPathIndex is a synchronous routine. assetForURL is an asynchronous routine. It will return the data long time after cellForRowAtPathIndex has returned.
Here's what you should do: Have a method cachedAssetForURL which returns the asset immediately, or returns nil. If it returns an asset, store it. Remember this has to be as efficient as possible, because this is called while the user scrolls up and down through the images.
If the method returns nil, trigger a download in the background. When that download finishes, don't even try to store the image in the cell - by this time, the same cell could display an entirely different object! Instead store the data so that cachedAssetForURL will be able to return the asset, and invalidate the row of your table view.
Fire a notification in the block (it's asynchronous), manage it by setting your imageview and reload your view.
The underlying issue I was encountering, as pointed out by #gnasher729, was the mishmash of synchronous and asynchronous calls. Rewriting the code to take this into account and to include a cache, I have the following working solution.
var cachedImages = [String:UIImage]()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let note = notes[indexPath.row]
let url = note.valueForKey("url") as! String
cell.textLabel!.text = note.valueForKey("title") as? String
cell.imageView!.image = UIImage(named: "note-icon")
if let image = cachedImages[url]{
cell.imageView!.image = image
} else {
let nsURL = NSURL(string: url)!
var loadError: NSError?
assetsLibrary!.assetForURL(nsURL, resultBlock: { (asset) -> Void in
if let ast = asset {
let image = UIImage(CGImage: ast.defaultRepresentation().fullResolutionImage().takeUnretainedValue())
self.cachedImages[url] = image
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
},failureBlock: {(error) -> Void in
loadError = error
})
}
return cell
}
This could be further improved to take more off of the main thread.

Resources