Image in table view [duplicate] - ios

This question already has an answer here:
Asynchronously load image in uitableviewcell
(1 answer)
Closed 5 years ago.
I have a problem with the image in table view cell
The images are downloaded form the Google Firebase and in every cell there is one of that
But when I scroll up or down the images change automatically the index
Here is my code, someone can help me? thanks a lot!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if postsArray[indexPath.row].imageNoImage == true{
let cell = tableView.dequeueReusableCell(withIdentifier: "imageLook", for: indexPath) as! imageLookTableViewCell
cell.authorLabel.text = self.postsArray[indexPath.row].author
cell.likesCountLabel.text = "\(self.postsArray[indexPath.row].likes!)"
cell.postID = postsArray[indexPath.row].postId
cell.textViewPost.text = self.postsArray[indexPath.row].textPost
let url = URL(string: postsArray[indexPath.row].pathToImage as! String)
if url != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if data != nil {
cell.imagePost.image = UIImage(data:data!)
}else{
}
}
}
}
for person in self.postsArray[indexPath.row].peopleWhoLike {
if person == FIRAuth.auth()!.currentUser!.uid {
cell.likesBtn.isHidden = false
break
}
}
return cell
}

Your question is not very descriptive/well written, but I think your problem is that you are not caching your images.
Try this:
let imageCache = NSCache()
let cell = tableView.dequeueReusableCell(withIdentifier: "imageLook", for: indexPath) as! imageLookTableViewCell
cell.authorLabel.text = self.postsArray[indexPath.row].author
cell.likesCountLabel.text = "\(self.postsArray[indexPath.row].likes!)"
cell.postID = postsArray[indexPath.row].postId
cell.textViewPost.text = self.postsArray[indexPath.row].textPost
let url = URL(string: postsArray[indexPath.row].pathToImage as! String)
if url != nil {
if let cachedImage = imageCache.objectForKey(url) as? UIImage {
cell.imagePost.image = cachedImage
return
}
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
if data != nil {
if let myImageName = UIImage(data:data!){
imageCache.setObject(myImageName, forKey: url)
}
cell.imagePost.image = UIImage(data:data!)
}else{
}
}
}
}
for person in self.postsArray[indexPath.row].peopleWhoLike {
if person == FIRAuth.auth()!.currentUser!.uid {
cell.likesBtn.isHidden = false
break
}
}
return cell
}

Related

How can I improve my cellForRowAt function?

I have read that the cellForRowAt method should not be to resource-intensive as it is called frequently while a user is scrolling through a TableView I tried to limit how much went into my cellForRowAt but seem to have overused it because anytime it is called scrolling is interrupted as it loads more data.
Here is my function:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(indexPath)
var post: PostStruct
var peopleUserIsFollowing: [String] = []
let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath) as! PostCell
cell.delegate = self
if postArray.count == 0 {
let instructions = cell.textLabel
instructions?.text = "Press the camera to start Piking!"
instructions?.textAlignment = .center
clearPosts(cell)
}else {
post = postArray[indexPath.row]
if let leftPostArray = userDefaults.array(forKey: fbLeftKey) as? [String]{
votedLeftPosts = leftPostArray
}
if let rightPostArray = userDefaults.array(forKey: fbRightKey) as? [String]{
votedRightPosts = rightPostArray
}
let firstReference = storageRef.child(post.firstImageUrl)
let secondReference = storageRef.child(post.secondImageUrl)
cell.firstImageView.sd_setImage(with: firstReference)
cell.secondImageView.sd_setImage(with: secondReference)
//For FriendsTableView query
let db = Firestore.firestore()
let followingReference = db.collection("following")
.document(currentUser!)
.collection("UserIsFollowing")
followingReference.getDocuments(){(querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
peopleUserIsFollowing.append(document.documentID)
}
}
}
//Fill in labels and imageViews
cell.timer = createTimer(post, cell)
cell.leftTitle.text = post.firstTitle
cell.rightTitle.text = post.secondTitle
cell.postDescription.text = post.postDescription
if post.userPic == "" {
userPic =
"Placeholder"
} else{
userPic = post.userPic
}
let url = URL(string: userPic)
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
cell.profilePic.image = UIImage(data: data!)
let votesCollection = db.collection("votes").document(post.postID)
getCount(ref: votesCollection, cell: cell)
if(post.uid != currentUser){
cell.userName.text = post.poster
}else{
cell.userName.text = "Me"
cell.tapLeft.isEnabled = false
cell.tapRight.isEnabled = false
}
cell.textLabel?.text = ""
if(post.poster == Auth.auth().currentUser!.uid || post.endDate - Int(NSDate().timeIntervalSince1970) <= 0){
cell.tapRight.isEnabled = false
cell.tapLeft.isEnabled = false
cell.firstImageView.layer.borderWidth = 0
cell.secondImageView.layer.borderWidth = 0
}
else if(votedRightPosts.contains(post.firstImageUrl)){
cell.secondImageView.layer.borderColor = UIColor.green.cgColor
cell.secondImageView.layer.borderWidth = 4
cell.firstImageView.layer.borderWidth = 0
cell.tapRight.isEnabled = false
cell.tapLeft.isEnabled = true
}
else if (votedLeftPosts.contains(post.firstImageUrl)){
cell.firstImageView.layer.borderColor = UIColor.green.cgColor
cell.firstImageView.layer.borderWidth = 4
cell.secondImageView.layer.borderWidth = 0
cell.tapLeft.isEnabled = false
cell.tapRight.isEnabled = true
}
}
return cell
}
I felt that the biggest issue would probably be the three images that are loaded into the cell but I am utilizing caching and when I commented out their loading I experienced the same issue. I have also read that utilizing a model can help which I believe that I did with the PostStruct object. I think I may need to pre-fetch however I cannot figure out where to even start with that. How can I improve my function so that scrolling in my app is smoother?
This would be a great place to use the Instruments tool. Run the time profiler on your app as you scroll through your table view. It will show you where the bulk of the delay is coming from.
Where are your images coming from? Are they loading from your local file system, or are those URLs network URLS?
You might need to refactor your code to return cells without the images, and trigger async code that loads the images in a background thread, installs them into your model, and then updates the cell once the images have finished loading.
I found out that this line of code was the issue:
if post.userPic == "" {
userPic =
"Placeholder"
} else{
userPic = post.userPic
}
let url = URL(string: userPic)
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
cell.profilePic.image = UIImage(data: data!)
In stead I changed it to utilize SDWebImage like the other two images in the post.

How to hide tableview until images are completely loaded iOS Swift?

My images take a second to load before they appear, which looks bad. On apps such as instagram, the tableview is hidden until the tableview is loaded... how do they do this? I have a loader that I want to display but don't know when to stop it and show tableview and detect the images have first finished loading? Where do I put stopTimer() ?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell",
for: indexPath) as! MainTableViewCell
let payment = self.payments[indexPath.row]
cell.profilePicture.layer.cornerRadius = cell.profilePicture.frame.size.width / 2
cell.profilePicture.clipsToBounds = true
if let profileImageUrl = payment.picture {
cell.profilePicture.loadImageUsingCacheWithUrlString(profileImageUrl)
}
if payment.message == "none" {
cell.detailsLabel.text = "No Message"
} else {
cell.detailsLabel.text = "\"\(payment.message ?? "")\""
}
}
MY CODE TO FETCH IMAGE IN TABLEVIEW:
let imageCache = NSCache<NSString, AnyObject>()
extension UIImageView {
func loadImageUsingCacheWithUrlString(_ urlString: String) {
self.image = nil
//check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
self.image = cachedImage
return
}
//otherwise fire off a new download
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
//download hit an error so lets return out
if let error = error {
print(error)
return
}
DispatchQueue.main.async(execute: {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString as NSString)
self.image = downloadedImage
}
})
}).resume()
}
}
You can simple use SDWebImage with cocoaPods and use it for async image downloader with cache support. Your cell will look like after ad SDWebImage.
import SDWebImage
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell",
for: indexPath) as! MainTableViewCell
let payment = self.payments[indexPath.row]
cell.profilePicture.layer.cornerRadius = cell.profilePicture.frame.size.width / 2
cell.profilePicture.clipsToBounds = true
if let profileImageUrl = payment.picture {
cell.profilePicture.sd_setImage(with: profileImageUrl, placeholderImage: UIImage(named: "yourPlaceholderImage.png"))
}
if payment.message == "none" {
cell.detailsLabel.text = "No Message"
} else {
cell.detailsLabel.text = "\"\(payment.message ?? "")\""
}
}
There is no need to hide tableView for downloading image.

Videos are placed on top of images in collection view?

I have a collection view which is populated with videos or images, based on what is fetched from firebase.
I am having this problem where when I fetch the data and add to the cells, some cells get a video added on top [of the image].
I have looked through the code found bellow and cant seem to . find where the problem is coming from.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "p1Item", for: indexPath) as! CollectionViewCell1
if postArray[indexPath.item].media[0].image != nil { //its an image
let date = ConvertDate(mediaTimestamp: postArray[indexPath.row].media[0].postNum!, isItForP3: false).getDate!
do {
cell.imageView.image = postArray[indexPath.item].media[0].image!
if postArray[indexPath.item].user.profileImageUrl != "" {
let url = URL(string: "\(postArray[indexPath.item].user.profileImageUrl)")
let data = try Data(contentsOf: url!)
if let profileImage = UIImage(data: data) {
cell.profImage.image = profileImage
cell.titleLabel.text = postArray[indexPath.item].user.username
cell.subtitleLabel.text = date
}
} else {
//I add a fake image here
cell.titleLabel.text = postArray[indexPath.item].user.username
cell.subtitleLabel.text = date
cell.profImage.image = UIImage(named: "media")
}
} catch {
print("need to add stuff to this catch")
}
} else { //its a video
let videoURL = postArray[indexPath.item].media[0].videoURL
let player = AVPlayer(url: videoURL! as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = cell.bounds
cell.layer.addSublayer(playerLayer)
let date = ConvertDate(mediaTimestamp: postArray[indexPath.item].media[0].postNum!, isItForP3: false).getDate!
do {
if postArray[indexPath.item].user.profileImageUrl != "" {
let url = URL(string: "\(postArray[indexPath.item].user.profileImageUrl)")
let data = try Data(contentsOf: url!)
if let profileImage = UIImage(data: data) {
cell.profImage.image = profileImage
cell.titleLabel.text = postArray[indexPath.item].user.username
cell.subtitleLabel.text = date
}
} else {
//I add a fake profile image here
cell.titleLabel.text = postArray[indexPath.item].user.username
cell.subtitleLabel.text = date
cell.profImage.image = UIImage(named: "media")
}
} catch {
print("need to add stuff to this catch")
}
}
print("Completed: ", cell.imageView!)
return cell
}
How do i fix this?
The reason is here
cell.layer.addSublayer(playerLayer)
you should clear the cell because it's dequeued
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "p1Item", for: indexPath) as! CollectionViewCell1
cell.layer.sublayers.forEach {
if $0 is AVPlayerLayer {
$0.removeFromSuperlayer()
}
}
, also you shouldn't use
let data = try Data(contentsOf: url!)
for remote data gribbing , you may use SDWebImage
When you say
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "p1Item", for: indexPath) as! CollectionViewCell1
This means that you are reusing the old cell and in your case the old cell might have a AVPlayerLayer
One way to fix this is to use different withReuseIdentifier
if postArray[indexPath.item].media[0].image != nil { //its an image
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImgageCell", for: indexPath) as! CollectionViewCell1
return cell
} else { //its a video
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! CollectionViewCell1
return cell
}
}
Or reset the Cell before reuse i.e. remove the layer after dequeueReusableCell

Swift Firebase UITableViewCell loads before Data to populate cell is available

I am pushing data which is an array of strings to a tableview controller. These strings are "uid's" which are users in my database. With this array I make a call to firebase to extract all users and then do a match to the uid's. I am getting the correct data, yet I print out everything to make sure when the data is available and the data is available only after the tableview cell loads which causes the data to be nil causing a crash or just empty data. How can I make the data load first and then the cell so the data is available for display?
I've created functions for the data and now I have it in my viewDidLoad. Also, you'll see I have tried adding the firebase call into the Cell setup but of course that does not work.
Array of strings
var data = [String]()
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
if snapshot.exists() {
self.businessUID = snapshot.value as? NSDictionary
if let dict = snapshot.value as? NSDictionary {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.businessDictionary = customerValue as! NSDictionary
print(self.businessDictionary)
print("Just printed the business dictionary")
}
}
}
}
} else {
print("does not exist")
}
})
}
Tableview Cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell
print(self.businessDictionary)
print("Print the dictionary here to check the values")
let businessValues = self.businessDictionary
let uid = self.data.description
print(businessValues)
print("printed the business values")
if let dict = businessValues {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.businessData = customerValue as? NSDictionary
print(self.businessData)
print("Printing matching the uid values")
}
}
}
}
cell.businessName.text = businessData?["businessName"] as? String
cell.businessStreet.text = businessData?["businessStreet"] as? String
cell.businessCity.text = businessData?["businessCity"] as? String
cell.businessState.text = businessData?["businessState"] as? String
let businessProfilePicture = businessData?["profPicString"] as? String
if (businessProfilePicture!.characters.count) > 0 {
let url = URL(string: (businessProfilePicture!))
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
}
} else {
let image = UIImage(named: "default")?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
return cell
}
Here is my solution. Got it to work. Appened and used "usersArray" to get and display the data.
var data = [String]()
var usersArray = [NSDictionary?]()
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("Businesses").observe(.value, with: { snapshot in
if snapshot.exists() {
self.businessUID = snapshot.value as? NSDictionary
if let dict = snapshot.value as? NSDictionary {
for item in dict {
let json = JSON(item.value)
let businessUid = json["uid"].stringValue
for uid in self.data {
if uid == businessUid {
let customerValue = self.businessUID?[uid]
self.usersArray.append(customerValue as! NSDictionary)
self.followUsersTableView.reloadData()
}
}
}
}
} else {
print("does not exist")
}
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.usersArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomerViewsSelectedBusinessesCell
let user : NSDictionary?
user = self.usersArray[indexPath.row]
cell.businessName.text = String(user?["businessName"] as! String)
cell.businessStreet.text = String(user?["businessStreet"] as! String)
cell.businessCity.text = String(user?["businessCity"] as! String)
cell.businessState.text = String(user?["businessState"] as! String)
let businessProfilePicture = String(user?["profPicString"] as! String)
if (businessProfilePicture.characters.count) > 0 {
let url = URL(string: (businessProfilePicture))
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
}
} else {
let image = UIImage(named: "default")?.potter_circle
cell.profileImage.contentMode = UIView.ContentMode.scaleAspectFill
cell.profileImage.image = image
}
return cell
}

Swift update tableview async with S3 download function

I have an async problem - I have a function that loads images from S3, stores them into an array of UIImages (here called Images)
I also have a tableview that loads its cells from firebase fetched data, my question is, how to update the cell image once the async finishes loading ?
I'm also afraid that the queue of images won't match exactly the indexPath.row since some images might load faster than other images.
func download(key:String, myindex:NSIndexPath, myrow:Int) -> NSString {
let path:NSString = NSTemporaryDirectory().stringByAppendingString("image.jpg")
let url:NSURL = NSURL(fileURLWithPath: path as String)
// let downloadingFilePath = downloadingFileURL.path!
let downloadRequest = AWSS3TransferManagerDownloadRequest()
downloadRequest.bucket = "witnesstest/" + rootref.authData.uid
downloadRequest.key = key
downloadRequest.downloadingFileURL = url
switch (downloadRequest.state) {
case .NotStarted, .Paused:
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.download(downloadRequest).continueWithBlock({ (task) -> AnyObject! in
if let error = task.error {
if error.domain == AWSS3TransferManagerErrorDomain as String
&& AWSS3TransferManagerErrorType(rawValue: error.code) == AWSS3TransferManagerErrorType.Paused {
print("Download paused.")
} else {
print("download failed: [\(error)]")
}
} else if let exception = task.exception {
print("download failed: [\(exception)]")
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let tempimage:UIImage = UIImage(contentsOfFile: path as String)!
print("dl ok")
self.Images.append(tempimage)
})
}
return nil
})
break
default:
break
}
return path
}
and the cell :
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MainWitnessTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("RIcell") as! MainWitnessTableViewCell
// populate the cell
let postitem = posts[indexPath.row]
cell.postOwner.text = postitem.author
cell.postContent.text = postitem.content
cell.postDate.text = postitem.createon
let myindex = indexPath
let myrow = indexPath.row
// cell.cellImage.image = Images[indexPath.row] // returns array index out of range
// download(postitem.imagekey, myindex: myindex, myrow: myrow)
return cell
}
You can just set the imageView's image after you download the image and at the same time set postitem's image property (assuming you add one). It's hard for me to understand everything your download method is doing, but I think the gist of what you want is something like:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MainWitnessTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("RIcell") as! MainWitnessTableViewCell
// populate the cell
let postitem = posts[indexPath.row]
cell.postOwner.text = postitem.author
cell.postContent.text = postitem.content
cell.postDate.text = postitem.createon
//postitem should also have a imageURL property or you should have some way of getting the image url.
if post item.image == nil{
dispatch_queue_t imageFetchQ = dispatch_queue_create("image fetcher", NULL)
dispatch_async(imageFetchQ, ^{
let imageData = NSData(contentsOfURL: postitem.imageURL)
let image = UIImage(data: imageData)
postitem.image = image
dispatch_async(dispatch_get_main_queue(), ^{
//the UITableViewCell may have been dequeued and reused so check if the cell for the indexPath != nil
if tableView.cellForRowAtIndexPath(indexPath) != nil{
cell.imageView.image = image
}
})
})
return cell
}
I would recommend you create a cache of images and the indices they're supposed to be associated with, and then instead of loading all the images in your function, you would create the table view, and then for that specific cell ask for the image from your server or from the cache if it's already there, rather then trying to download them all async at one time

Resources