i am new to swift, currently making a personal app,
i am trying to load this image
my image url
after that i used this code on my table view to load the image
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let url = posts[indexPath.row].message
let url1 = URL(string: url!)
let data = try? Data(contentsOf: url1!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
MoviePoster.image = UIImage(data: data!)
self.tableView.reloadData()
return cell
}
but instead of images, the screen looks like this
screen image
any help would be appreciated
First of all when implementing tableView you need to set delegate and datasource of your tableView in your viewDiLoad
like this.
yourTableView.datasource = self
yourTableView.delegate = self
before this you need to extend your tableView like this and i think you did already.
Now comes to the downloading part of your image. As you are new, the process by which you are downloading this image is not correct.
why?
you mentioned reloadData() in cellForRowAtIndexPath which is totally wrong.just check online answer for this.
Secondly your view might get in hang state because if your image is large then it will take time to show you image.So it might be that, you won't see anything or you view will not load either.
How to resolve this?
Download image using asynchronous way.And anything you want to download call it in viewDidAppear.
Is there any library as a shortcut?
Yes. Use SDWebImage. It's a great library. You don't have to think about all thing.It already did the job. All you have to do is to call. just like this.
imageView.sd_setImage(with: URL(string: "yourdomainpathforImage"), placeholderImage: UIImage(named: "placeholder.png"))
Check out this from here.
Related
The scroll performance of my app when it downloads high resolutions images from IMGUR is slow and sluggish. Images are oddly dequeuing and rendering. Below is the code that downloads the image. I don't think the caching mechanism is working. How do I fix this?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoTableViewCell", for: indexPath) as! PhotoTableViewCell
cell.descrpiptionLabel.text = photos[indexPath.row].title ?? "No Description"
cell.photoImageView.downloadImage(from: images[indexPath.row])
return cell
}
let imageCache = NSCache<NSString,AnyObject>()
extension UIImageView {
func downloadImage(from urlString: String ) {
guard let url = URL(string: urlString) else { return }
storeCache(url: url)
}
func storeCache(url:URL){
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) as? UIImage {
self.image = cachedImage
}else {
let _: Void = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let self = self else { return }
if error != nil { return }
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: url.absoluteString as NSString)
self.image = downloadedImage
}
}
}.resume()
}
}
}
There is a performance issue here, namely if you scroll quickly, the images for latter cells will get backlogged behind image requests for cells that are no longer visible.
To fix this, the UIImageView extension should save a reference to the URLSessionDataTask, and downloadImage should see if there is an request in progress, and if it is for a different URL (presumably for a cell that is no longer visible), it should cancel that request before starting another network request for the visible cell.
The only trick is that extensions cannot add stored properties, so you will have to use “associated objects” (e.g., objc_getAssociatedObject and objc_setAssociatedObject) to keep track of these references.
See downloading and caching images from url asynchronously for example implementation.
Unrelated to your question, downloadImage should, before initiating an asynchronous network request, set the image to nil or to a placeholder image. If a cell is reused, the last image will be shown until the download is done. Make sure to initialize the image before starting an asynchronous process, to make sure you don’t see the old image until the new one is retrieved.
Above I answered the performance question if you scroll quickly, where images will appear very slowly. That having been said, there is a second performance issue, namely that you are caching and using images that are larger than what is required by your UI. This can cause a different performance problem, notably hitches in your UI as you scroll (momentary hesitations that will prevent scrolling from happening smoothly).
If you see this (and presuming you can’t just request thumbnails from your backend, which is the best solution), you should resize your images to thumbnail size when you cache them. Or, if you will need the high resolution images later, have two caches, one for the full size images and another for the thumbnails.
Let’s say your image view is 50×50pt on a retina device with 3× scaling. So you will want to resize your downloaded image to 150×150px, and cache that.
If you use much larger assets for small image views, the device will have to continue to resize them on the fly, which, if the images are very large, is so computationally expensive that you will see the hitches in the scrolling behavior. If your images are just a little too big, resizing on the fly will probably not be a problem. But if you don’t have smooth scrolling and the assets are very big, resize them before caching.
For your issue where the previous image is showing when the cell is reused, you should override func prepareForReuse() in PhotoTableViewCell and set photoImageView.image = nil.
For your performance issue, it looks like you're making the API request off the main thread, so that's a good start. How large are the images you're requesting? I'm wondering if the data is so large that it's taking a lot of time to convert it to an image and then set the image on the image view
Currently,
I have a feed for the user and
it uses uitableview and
there is a uicollectionview inside tableview for multi-images.
'Like' or 'Comment' functions are working well
but some issues happen when user taps 'Like'.
I do not want to show several changes,
but when user taps 'Like', I need to reload a cell and it shows another picture for a short time(bcs of reuse) and back to original image.
I tried to use the function, prepareForReuse().
However, I am not sure how to maintain the same image currently on the screen when they are reloading. Any idea u have?
For ur more information,
let me show my tableview's part of 'CellForItemAt' and collectionview's same method.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "storyCell", for: indexPath) as! StoryPhotoCollectionViewCell
let imageURL = photoList[indexPath.row]
let url = URL(string: imageURL)
DispatchQueue.main.async {
cell.imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "imageplaceholder"), options: nil, progressBlock: nil, completionHandler: nil)
}
cell.imageView.kf.indicatorType = .activity
return cell
}
The collectionView's datasource is photoList array, so in the tableview, I have this code.
DispatchQueue.main.async {
cell.photoList = (story.imageArray?.components(separatedBy: ",").sorted())!
}
The issue should be due to delay in asynchronous download of the image,
I believe your code would be like this
cell.image = downloadFromURL(SOME_URL)
Add this single line code before assigning the image
cell.image = nil; // or some placeholder image
cell.image = downloadFromURL(SOME_URL)
If possible please provide more info
If I understand well your question, you need:
When the status change, you change the image so, this image can be stored as part of the app or external. If it is the same image, you need to keep it cached.
You start a timer like:
let countTimeBeforeChangeMyImageBack = DispatchTime.now() + .seconds(waitTimeBeforeStartCounting)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: {
self.YourMethodToChangeYourImageBack
})
At your method YourMethodToChangeYourImageBack you set the original image back.
Here, remember you could need to join back to the main thread before updating the UI:
// Re join the main queue after the callback
DispatchQueue.main.sync() {
// Your code to update the image
}
Hope it Helps.
I have a tableview where I am trying to load videos and play them on viewdidLoad()
Following is the code for load video on Viewdidload
func playVideo(viewController:UIViewController,videoPath:String!, view: UIView) {
guard let path = videoPath else {
debugPrint("video.m4v not found")
return
}
let url = NSURL.fileURL(withPath: path)
let item = AVPlayerItem(url: url)
self.player = AVPlayer(playerItem: item)
self.videoPlayerController = AVPlayerViewController()
self.videoPlayerController.player = self.player
videoPlayerController.view.frame = view.bounds
viewController.addChildViewController(videoPlayerController)
view.addSubview(videoPlayerController.view)
}}
Inside cellForRowAtIndexPath I'm doing the following
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
cell = tableView.dequeueReusableCell(withIdentifier: "trendViewControllerCell", for: indexPath) as! TrendViewTableCell
cell.videoName.text = feeds[indexPath.row].videoTitle
cell.artistName.text = feeds[indexPath.row].artistName
player.playVideo(viewController: self, videoPath: Bundle.main.path(forResource: feeds[indexPath.row].videoUrl, ofType:"mp4")!, view: cell.videoView)
return cell
}
I am trying to resize the AVPlayerController to the view in tableView cell.
On viewDidLoad I am able to see an AVPlayer controller for all views in the cells.
There are about 15 videos
As I scroll down further I see a cancelled buttons and none of the videos load. Sometimes all the videos load and sometimes they don't.
However I don't see this problem in the simulator.
How can I solve this problem? Any help will be appreciated
Sorry but your approach is not a good idea: have a single AVPlayer for every cell is very heavy and you can encounter lots of problems related like reload the video every time your cell appears, jerky scrolling, bad performance, etc.
In addition keep in mind that AVPlayer is instantiated always in the main thread, so while scrolling you shouldn't instantiate any other player video otherwise you keep busy the main thread (the same thread that does UI updates!).
Like Instagram and Facebook do the common approach here is have a common instance of an AVPlayer video and images of the first or last frame for every video: when your cell is completely visibile put over the image your video player view passing the video url using replaceCurrentItemWithPlayerItem.
It's not an easy and quick thing to do so take your time and be patience, with time you will build your solution; you can find more info on these questions:
AVPlayerItem replaceCurrentItemWithPlayerItem Blocking
Maintaining good scroll performance when using AVPlayer
I have a tableview that I created with code (without storyboard):
class MSContentVerticalList: MSContent,UITableViewDelegate,UITableViewDataSource {
var tblView:UITableView!
var dataSource:[MSC_VCItem]=[]
init(Frame: CGRect,DataSource:[MSC_VCItem]) {
super.init(frame: Frame)
self.dataSource = DataSource
tblView = UITableView(frame: Frame, style: .Plain)
tblView.delegate = self
tblView.dataSource = self
self.addSubview(tblView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
let record = dataSource[indexPath.row]
cell.textLabel!.text = record.Title
cell.imageView!.downloadFrom(link: record.Icon, contentMode: UIViewContentMode.ScaleAspectFit)
cell.imageView!.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
print(cell.imageView!.frame)
cell.detailTextLabel!.text = record.SubTitle
return cell
}
}
and in other class I have an extension method for download images Async:
extension UIImageView
{
func downloadFrom(link link:String?, contentMode mode: UIViewContentMode)
{
contentMode = mode
if link == nil
{
self.image = UIImage(named: "default")
return
}
if let url = NSURL(string: link!)
{
print("\nstart download: \(url.lastPathComponent!)")
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, _, error) -> Void in
guard let data = data where error == nil else {
print("\nerror on download \(error)")
return
}
dispatch_async(dispatch_get_main_queue()) { () -> Void in
print("\ndownload completed \(url.lastPathComponent!)")
self.image = UIImage(data: data)
}
}).resume()
}
else
{
self.image = UIImage(named: "default")
}
}
}
I used this function in other places and worked correctly, Based on my logs I understand that images downloaded without problem (when the cell is rendered) and after download of image, The cell UI not updated.
Also I tried to use caching library like Haneke but problem is exist and not change.
Please help me to understand mistakes
Thanks
After setting the image you should call self.layoutSubviews()
edit: corrected from setNeedsLayout to layoutSubviews
The issue is that the .subtitle rendition of UITableViewCell will layout the cell as soon as cellForRowAtIndexPath returns (overriding your attempt to set the frame of the image view). Thus, if you are asynchronously retrieving the image, the cell will be re-laid out as if there was no image to show (because you're not initializing the image view's image property to anything), and when you update the imageView asynchronously later, the cell will have already been laid out in a manner such that you won't be able to see the image you downloaded.
There are a couple of solutions here:
You can have the download update the image to default not only when there is no URL, but also when there is a URL (so you'll first set it to the default image, and later update the image to the one that you downloaded from the network):
extension UIImageView {
func download(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFill, placeholder: UIImage? = nil) {
contentMode = mode
image = placeholder
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let response = response as? HTTPURLResponse, error == nil else {
print("error on download \(error ?? URLError(.badServerResponse))")
return
}
guard 200 ..< 300 ~= response.statusCode else {
print("statusCode != 2xx; \(response.statusCode)")
return
}
guard let image = UIImage(data: data) else {
print("not valid image")
return
}
DispatchQueue.main.async {
print("download completed \(url.lastPathComponent)")
self.image = image
}
}.resume()
}
}
This ensures that the cell will be laid out for the presence of an image, regardless, and thus the asynchronous updating of the image view will work (sort of: see below).
Rather than using the dynamically laid out .subtitle rendition of UITableViewCell, you can also create your own cell prototype which is laid out appropriately with a fixed size for the image view. That way, if there is no image immediately available, it won't reformat the cell as if there was no image available. This gives you complete control over the formatting of the cell using autolayout.
You can also define your downloadFrom method to take an additional third parameter, a closure that you'll call when the download is done. Then you can do a reloadRowsAtIndexPaths inside that closure. This assumes, though, that you fix this code to cache downloaded images (in a NSCache for example), so that you can check to see if you have a cached image before downloading again.
Having said that, as I alluded to above, there are some problems with this basic pattern:
If you scroll down and then scroll back up, you are going to re-retrieve the image from the network. You really want to cache the previously downloaded images before retrieving them again.
Ideally, your server's response headers are configured properly so that the built in NSURLCache will take care of this for you, but you'd have to test that. Alternatively, you might cache the images yourself in your own NSCache.
If you scroll down quickly to, say, the 100th row, you really don't want the visible cells backlogged behind image requests for the first 99 rows that are no longer visible. You really want to cancel requests for cells that scroll off screen. (Or use dequeueCellForRowAtIndexPath, where you re-use cells, and then you can write code to cancel the previous request.)
As mentioned above, you really want to do dequeueCellForRowAtIndexPath so that you don't have to unnecessarily instantiate UITableViewCell objects. You should be reusing them.
Personally, I might suggest that you (a) use dequeueCellForRowAtIndexPath, and then (b) marry this with one of the well established UIImageViewCell categories such as AlamofireImage, SDWebImage, DFImageManager or Kingfisher. To do the necessary caching and cancelation of prior requests is a non-trivial exercise, and using one of those UIImageView extensions will simplify your life. And if you're determined to do this yourself, you might want to still look at some of the code for those extensions, so you can pick-up ideas on how to do this properly.
--
For example, using AlamofireImage, you can:
Define a custom table view cell subclass:
class CustomCell : UITableViewCell {
#IBOutlet weak var customImageView: UIImageView!
#IBOutlet weak var customTitleLabel: UILabel!
#IBOutlet weak var customSubtitleLabel: UILabel!
}
Add a cell prototype to your table view storyboard, specifying (a) a base class of CustomCell; (b) a storyboard id of CustomCell; (c) add image view and two labels to your cell prototype, hooking up the #IBOutlets to your CustomCell subclass; and (d) add whatever constraints necessary to define the placement/size of the image view and two labels.
You can use autolayout constraints to define dimensions of the image view
Your cellForRowAtIndexPath, can then do something like:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
let record = dataSource[indexPath.row]
cell.customTitleLabel.text = record.title
cell.customSubtitleLabel.text = record.subtitle
if let url = record.url {
cell.customImageView.af.setImage(withURL: url)
}
return cell
}
With that, you enjoy not only basic asynchronous image updating, but also image caching, prioritization of visible images because we're reusing dequeued cell, it's more efficient, etc. And by using a cell prototype with constraints and your custom table view cell subclass, everything is laid out correctly, saving you from manually adjusting the frame in code.
The process is largely the same regardless of which of these UIImageView extensions you use, but the goal is to get you out of the weeds of writing the extension yourself.
oh my god, the layoutSubviews is not recommended to use directly
the right way to solve the problem is call:
[self setNeedsLayout];
[self layoutIfNeeded];
here, the two way have to call together.
try this, have a good luck.
Create your own cell by subclassing UITableViewCell. The style .Subtitle, which you are using, has no image view, even if the property is available. Only the style UITableViewCellStyleDefault has an image view.
Prefer SDWebImages library here is the link
it will download image async and cache the image also
and very easy to integrate into the project as well
I have a tableView with dynamic cells. Each cell has got an imageView and a textLabel. I'm working with Alamofire & AlamofireImage by the way.
My problem is that the first cells (which you see if view did appear) don't show the images. But if i scroll down i see the images of the other cells. And if scroll up again the images of the first cells appear too.
First of all i download user data in the viewDidLoad method. After this is done I update the tableview with tableView.reloadData().
override func viewDidLoad() {
super.viewDidLoad()
MYRequest_getUsers(//...
,
success: {response -> Void in
self.users = response
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
},
failure: {NSError -> Void in
debugPrint(NSError)
})
}
TableView counts the users and reloads itself.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users?.count ?? 0
}
In tableView_cellForRowAtIndexPath method i fill the cells with user data.
let cell = tableView.dequeueReusableCellWithIdentifier(self.identifier) as! UserCell
cell.userNameLabel.tag = indexPath.row
let rowData: User = self.users?[cell.userNameLabel.tag] as User!
cell.userNameLabel.text = rowData.getName()
let avatarURL = rowData.getAvatarURL() ?? ""
cell.userImageView.af_setImageWithURL(imgURL, placeholderImage: placeholderImage)
return cell
My idea was that after user data was loaded, the tableView begin to draw itself and place the name (because it is already in userData). But the image is downloaded (i suppose) asynchronously, so that they come from the backend after some delay and tableView is already drawn. After scrolling up and down i see them.
I want to open the screen and without scrolling up and down. Tableview should set automatically the images after they were loaded. So i thought to make a callback and use instead of
cell.userImageView.af_setImageWithURL(imgURL, placeholderImage: placeholderImage)
this
Alamofire.request(.GET, avatarURL)
.responseImage { response in
cell.userImageView.image = response.2.value
dispatch_async(dispatch_get_main_queue(), { () -> Void in
tableView.setNeedsLayout()
})
}
But nothing changes... I've tried a lot and looked similar problems but can't solve it... I hope you can give me some hints or much better a solution! :)
Thanks in advance
I would like to give you a direction by posting the steps (best practice to follow in such case):
Step 1 : Fetch images in background as soon as you have image URLs available from server. I prefer doing this on operation queue where I download multiple images concurrently. You can write a helper class which takes a completion block and implement NSOperation/NSOperationQueue.
Step 2 : While images are being downloaded, for the eyes of users, put a loading overlay on image view. You can do this in cellForRowAtIndexPath:.
Step 3 : Once images are available, cache them in file system. This is to avoid any scrolling abrupt behaviour.
Step 4 : Once images are available, call the completion block.
Step 5 : In completion block, reload your table on main thread. Ensure your cellForRowAtIndexPath: first check the image in cache, if present use it, if not present show loading overlay if image fetch is on flight. If image is not available in cache and download is also not going on, show some default image.
This question is couple of years old, but maybe this answer can be useful to someone else with a similar problem, like me before to find the right solution.
Since the images are loaded asynchronously, we have to force a cell update when the download is finished if we didn't provide a fixed height for the UIIMageView. This because cell updating (i.e. AutoLayout Constraints recalculation) is done automatically only after cellForRowAt method, that is called when a cell is displayed for the first time, or when the table is scrolled to show other cells. In both cases probably the images are not yet downloaded by the af_setImage() method, so nothing but the placeholder will be displayed as their sizes are unknown for the moment.
To force a cell update we need to use beginUpdates() and endUpdates() methods, putting them inside the completion handler of .af_setImage(). This way, every time the downloading is completed, the cell will be updated.
But, to avoid a loop, before to call beginUpdates()/endUpdates() we have to check if we have already update the cell before, because by calling these methods, the cellForRowAt method is called again and consequently the af_setImage() and its completion closure with beginUpdates()/endUpdates() inside it).
This means that we have to update the cell only when the download is just finished, and not when the imaged is cashed (because, if it is cashed, it means that we have already updated the cell). This can be accomplished by checking the response of the completion handler: if it is not nil, the image was just downoladed, if it is nil, the image was cashed.
As a side benefit the cell height will be automagically adjusted (remember to put tableView.estimatedRowHeight = 400 and tableView.rowHeight = UITableViewAutomaticDimension in your viewDidLoad() method)
Finally, here it is the code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue your cell
let cell = self.tableView.dequeueReusableCell(withIdentifier: "YourCustomCellIdentifier") as! YourCustomTableViewCell
// get picture url from the data array
let pictureUrl = self.yourCellsData[indexPath.row].pictureUrl
// async download
cell.pictureView.af_setImage(
withURL: URL(string: pictureUrl)!,
placeholderImage: UIImage(named: "YourPlaceholder.png"),
filter: nil,
imageTransition: UIImageView.ImageTransition.crossDissolve(0.5),
runImageTransitionIfCached: false) {
// Completion closure
response in
if response.response != nil {
// Force the cell update
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
return cell
}
That's all folks! ;-)
Few things to achieve this.
call data download in viewwillappear and not in viewdidload.
in viewdidload, hide the tableview.
in viewdidAppear: check the data has downloaded and if so then call
[tableview reloaddata] method.