UIImage from url takes long time to load swift - ios

I have a UITableView with A lot of UITableViewCell, I use this code to load content and images to the UITableCell but it takes long time for the image to show for each UITableViewCell.
var loadOnce : [String] = []
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("ProfileActivities", forIndexPath: indexPath) as! ProfileActivitiesTableViewCell
if !loadOnce.contains("\(indexPath.row)") {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let LocationImage = self.postmap[indexPath.row]
let LocationImageUrl = NSURL(string: LocationImage)
let LocationImageData = NSData(contentsOfURL: LocationImageUrl!)
let ProfileImage = self.postimg[indexPath.row]
let ProfileImageUrl = NSURL(string: ProfileImage)
let ProfileImageData = NSData(contentsOfURL: ProfileImageUrl!)
dispatch_async(dispatch_get_main_queue(), {
cell.locationImg.image = UIImage(data: LocationImageData!)
cell.activitesProfileImg.image = UIImage(data: ProfileImageData!)
});
});
loadOnce.append("\(indexPath.row)")
}
return cell
}
Putting the code in dispatch_async made scrolling smother but its still takes time to load images.
how to make it load images faster considering I have to many images something like Facebook or Instagram.
Thanks.

There will be issue because of Async call and ReUsability. Lets say your Image at IndexPath 1 is loading image but it is still taking time to download and meanwhile user scrolled down at some another index i.e. 15 and Internally the same cell of Index 1 is alloted to Index 15 and Image of cell 1 will be displayed in Cell 15 if you have not managed to handle previous calls for same instance of cell. Thats why its Better to use some caching library like SDWebImage(As #SeanLintern88 said) or AFNetworking's UIImageView Category
AlamoFire's UIImageView (For Swift)
Event if you wanted to do this, then better is to go with subclassing, it will help you to manage the Calls and Its termination.
In your case the Loading of Image might be because of Size of actual image that you are loading from server. CDN kind of service provide some easy to implement techniques to serve different size of images as per the request. So even If User has uploaded 1200x1200 sized image but on list screen you can fetch its 120x120 sized image, This helps is faster loading as well as it will save Physical Memories.

Use one of the following libraries to asynchronously load images to you view :
1) Asyncimageview https://github.com/nicklockwood/AsyncImageView
2) SDWebImage https://github.com/rs/SDWebImage

It sounds like your image sizes could be large as the code looks fine, usually apps like FB/Insta would use low res renditions and then load in higher res after/when needed.
Most people use an image fetching library such as SDWebImage as this will async fetch the images and cache them so you don't have to save them on your model and consume the memory.
https://github.com/rs/SDWebImage

Related

Does showing system image(SF symbols) use a networking call in Swift?

I'm creating an application in ios where I load images from an api using a UITableView and UITableViewCell.
Since the UITableView reuses cells, old images were appearing when I scroll fast. In order to prevent this, I set a default image using a system image(SF symbols).
I also use a cache to store urls to images.
Everything works as it should but now I think of it I'm sending a network request to retrieve that systemImage each time which seems incredibly inefficient since I was using a cache in order to reduce the total network calls in the first place.
Is there way around this or is this a tradeoff I must make?
Code is below.
//use default image from SF symbols
let defaulticon = UIImage(systemName: "photo")?.withTintColor(.gray, renderingMode: .alwaysOriginal)
DispatchQueue.main.async {
cell.mealImage.image = defaulticon
}
guard cell.meal?.strMealThumb != nil else {
print("Category Image doesn't exist")
return
}
//use cache
if let imageData = model.imagecache.object(forKey: cell.meal!.strMealThumb as NSString) {
print("using cache")
DispatchQueue.main.async {
cell.mealImage.image = imageData
}
}
else {
let url = URL(string: cell.meal!.strMealThumb)
let session = URLSession.shared.dataTask(with: url!) { data, response, error in
if error == nil && data != nil {
let image = UIImage(data: data!)
//self.model.imagecache[cell.meal!.strMealThumb] = image
self.model.imagecache.setObject(image!, forKey: cell.meal!.strMealThumb as NSString)
DispatchQueue.main.async {
cell.mealImage.image = image
}
}
}
session.resume()
}
}
Override prepareForReuse method in UITableViewCell and add code in this function to clean up unrequited data that could persist from previous usage of the cell. In your example assign the default image in this function to produce better result.
You asked:
I set a default image using a system image(SF symbols).
...
Everything works as it should but now I think of it I'm sending a network request to retrieve that systemImage each time which seems incredibly inefficient since I was using a cache in order to reduce the total network calls in the first place.
No, UIImage(systemName:) does not make a network request. And it caches the image, itself, as the documentation says:
This method checks the system caches for an image with the specified name and returns the variant of that image that is best suited for the main screen. If a matching image object is not already in the cache, this method creates the image from the specified system symbol image. The system may purge cached image data at any time to free up memory. Purging occurs only for images that are in the cache but are not currently being used.
FWIW, you can empirically verify that this does not perform a network request disconnecting from the network and trying to use it. You will see it works fine, even when disconnected.
FWIW, there is a very small performance gain (less than a millisecond?) by keeping a reference to that tinted system image and reusing it, rather than fetching the cached system image and re-tinting it. But the performance improvement is negligible.

Swift cache base64 string UIImage data

I'm trying to cache UIImage that images come from service(I'm using Alamofire). Service sends me a base64 string and I'm converting base64 to data then print in tableviewcell with
cell.imageview.image = UIImage(data: imageDatas[indexPath.row])
I searched lots of libraries like Kingfisher , AlamofireImage but they are caching URL image can't find anyway to cache image with base64 string.So I find a similar example and try this :
private let cache = NSCache<NSNumber, UIImage>()
private let utilityQueue = DispatchQueue.global(qos: .utility)
private func loadImage(data : Data , completion: #escaping (UIImage?) -> ()) {
utilityQueue.async {
let image = imageDataDecodingClass.imageDataDecoding(imageData: data)
DispatchQueue.main.async {
completion(image)
}
}
}
in cell :
let itemNumber = indexPath.section * 2 + 1
let imageData = (showcaseDatas[indexPath.section * 2 + 1].Document?.Document!)!
if let cachedImage = self.cache.object(forKey: NSNumber(value: itemNumber)) {
cell.showcaseImage.image = cachedImage
} else {
cell.addSubview(progressHUDimage)
self.loadImage(data: imageData, completion: {ret in
cell.showcaseImage.image = ret
self.cache.setObject(cell.showcaseImage.image!, forKey: NSNumber(value: itemNumber))
progressHUDimage.removeFromSuperview()
})
}
Its caching image perfectly but when I scroll tableview ,CPU increased a lot (%70-90) thats why tableview is not smoothing.
So , my question is , How can I cache base64 string image in tableviewcell with smoothing and without CPU increased ? Thanks
If you are caching base64 String or Data there will be always a hit in decoding them as an image. The only way it would be caching the UIImage itself, but this will come with trade off of memory depending on the size of your images.
I can only give you few advices:
Use NSCache (it seems that you are already using it)
Resize your images on another thread to have a perfect fit on the size that you are rendering on screen and cache them only after they have been resized
Be sure that the performance hit you are seeing is not due to other reasons
Cache images by using their index path if you are using for cells
Create your NSCache with a memory limit and a number of element limit
You can also try to create 2 caches, one for ready to go already decode images and the other one as a fallback with Data object.
The fact that your Data objects are small it doesn't means that also images are, it really depends on the compression that has been used to save the image representation.
There are also more advance technique using memory mapping on physical memory.

Retrieve Multiple Images Using PHAsset

I'm trying to retrieve over 1,000 images from the user's camera roll with PHAsset but it ends up crashing or taking a long time if it's just thumbnails. Here is my function where I retrieve the images...
func retrieveImages(thumbnail: Bool) {
/* Retrieve the items in order of modification date, ascending */
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "modificationDate",
ascending: false)]
/* Then get an object of type PHFetchResult that will contain
all our image assets */
let assetResults = PHAsset.fetchAssetsWithMediaType(.Image,
options: options)
let imageManager = PHCachingImageManager()
assetResults.enumerateObjectsUsingBlock{(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset{
let asset = object as! PHAsset
print("Inside If object is PHAsset, This is number 1")
var imageSize: CGSize!
if thumbnail == true {
imageSize = CGSize(width: 100, height: 100)
} else {
imageSize = CGSize(width: self.cameraView.bounds.width, height: self.cameraView.bounds.height)
}
/* For faster performance, and maybe degraded image */
let options = PHImageRequestOptions()
options.deliveryMode = .FastFormat
options.synchronous = true
imageManager.requestImageForAsset(asset,
targetSize: imageSize,
contentMode: .AspectFill,
options: options,
resultHandler: { (image, _: [NSObject : AnyObject]?) -> Void in
if thumbnail == true {
self.libraryImageThumbnails.append(image!)
self.collectionTable.reloadData()
} else {
self.libraryImages.append(image!)
self.collectionTable.reloadData()
}
})
/* The image is now available to us */
print("enum for image, This is number 2")
print("Inside If object is PHAsset, This is number 3")
}
print("Outside If object is PHAsset, This is number 4")
}
}
Please tell me if any more information is needed. Thank you!
Generally you don't want to be loading tons of full-size or screen-sized images and keeping them in memory yourself. For that size, you're only going to be presenting one (or two or three, if you want to preload for screen-transition animations) at a time, so you don't need to fetch more than that at once.
Similarly, loading hundreds or thousands of thumbnails and caching them yourself will cause you memory issues. (Telling your collection view to reloadData over and over again causes a lot of churn, too.) Instead, let the Photos framework manage them — it has features for making sure that thumbnails are generated only when needed and cached between uses, and even for helping you with tasks like grabbing only the thumbnails you need as the user scrolls in a collection view.
Apple's Using Photos Framework sample code project shows several best practices for fetching images. Here's a summary of some of the major points:
AssetGridViewController, which manages a collection view of thumbnails, caches a PHFetchResult<PHAsset> that's given to it upon initialization. Info about the fetch result (like its count) is all that's needed for the basic management of the collection view.
AssetGridViewController requests thumbnail images from PHImageManager individually, only when the collection view asks for a cell to display. This means that we only create a UIImage when we know a cell is going to be seen, and we don't have to tell the collection view to reload everything over and over again.
On its own, step 2 would lead to slow scrolling, or rather, to slow catch-up of images loading into cells after you scroll. So, we also do:
Instead of using PHImageManager.default(), we keep an instance of PHCachingImageManager, and tell it what set of images we want to "preheat" the cache for as the user scrolls.
AssetGridViewController has some extra logic for keeping track of the visible rect of the scroll view so that the image manager knows to prepare thumbnails for the currently visible items (plus a little bit of scroll-ahead), and can free resources for items no longer visible if it needs to. Note that prefetching doesn't create UIImages, just starts the necessary loading from disk or downloading from iCloud, so your memory usage stays small.
On selecting an item in the collection view (to segue to a full-screen presentation of that photo), AssetViewController uses the default PHImageManager to request a screen-sized (not full-sized) image.
Opportunistic delivery means that we'll get a lower-quality version (basically the same thumbnail that Photos has already cached for us from its previous use in the collection view) right away, and a higher quality version soon after (asynchronously, after which we automatically update the view).
If you need to support zooming (that sample code app doesn't, but it's likely a real app would), you could either request a full-size image right away after going to the full-screen view (at the cost of taking longer to transition from blown-up-thumbnail to fullscreen image), or start out by requesting a screen-sized image and then also requesting a full-sized image for later delivery.
In CellForRowAtIndexPath use the PHImageManager's RequestImageForAsset method to lazy load the image property on your UIImageView.

populate UITableView with Json image URL calls swift

I'm new into programming in Swift and so far I'm downloading Json data as Strings and populate a UITableView. The images inside are url links. The problem is that the data are many, 53, so 53 url calls to get the images as well. At first, I was doing everything in the main thread so it was lagging a lot. Now I've put the code that does the http calls in an async method. The app does not lag but
1) The images don't download in order (I don't mind about that much although it would be nicer)
2) The download is slow, the memory hits around 250-270mb and the cpu around 40-50% while the network is around 500kb/s.
I don't own an iPhone to do a real check but with those numbers I see that the app uses a lot of resources. I wonder why the network is so slow though. Using 3g-4g must be faster and less stressing in my opinion and I don't know what the emulator is using.
So my question, is there any way for my app to go any faster or use less resources?
Below the code that puts the data on the TableView. It takes below 2 seconds to fill the table with the strings and a lot of time to download all the images.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "GameTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! GameTableViewCell
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
cell.nameLabel?.text = games[indexPath.row].name
cell.releaseDateLabel?.text = games[indexPath.row].releaseDate
dispatch_async(backgroundQueue, {
for _ in self.games{
if let url = NSURL(string: self.games[indexPath.row].gameImage!) {
if let data = NSData(contentsOfURL: url){
cell.photoImageView?.contentMode = UIViewContentMode.ScaleAspectFit
cell.photoImageView?.image = UIImage(data: data)
}
}
}
})
return cell
}
You're downloading the images every time you want to show a cell. You need to use NSCache or any other third-party solution or something as simple as NSMutableDictionary for caching the images that downloads successfully so you don't download them every time.
You can also use the existing third-party solutions like AlamofireImage and SDWebImage which provide async downloading of images, showing placeholder image, and caching
I was skeptical because I have never used an outside library but erasing 5-10 lines of code to just type the code below.. well, it saves a lot of time and trouble.
if let url = NSURL(string: self.games[indexPath.row].gameImage!) {
cell.photoImageView?.hnk_setImageFromURL(url)
}

UIscrollView image from web in swift

I want to make a gallery with UIScrollview like this.
In case, I want to get the images from web, but with this code my VC is very slow to load
var pageImage: [UIImage] = []
for d in image {
var imgUrl: NSURL = NSURL(string: "https://images.com/\(d.thumbnail)")!
var imgData = NSData(contentsOfURL: imgUrl)
pageImage.append(UIImage(data: imgData!)!)
}
How to make my VC load faster?
Only load the images when you actually need them. Use the scroll view delegate to find out when an image is about to appear on screen.
You should also not fetch the images on the UIThread which will make the app feel unresponsive. I would recommend using a 3rd party lib for loading and displaying the images such as SDWebImage or AFNetworking+UIImageView
as eric said you are loading imae on main thread you can set image in swift with url like imageView.setImageWithURL
or you can load image with background thread

Resources