Tableview Feed Images - ios

I developing news app. I using RSS feed with XML Parsing. I want RSS feed add images. I have defined the necessary function for images. But I do not know how to use a variable when I get the photo in RSS. My application is currently receiving the photo from the URL. All photos are the same. How can I do that? Sorry for my bad English.
//UItableView Data source
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return haberler.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell:EmojiTableViewCell = tableView.dequeueReusableCell(withIdentifier: "myCell")! as UITableViewCell as! EmojiTableViewCell
if (cell.isEqual(NSNull.self))
{
cell = Bundle.main.loadNibNamed("myCell", owner: self, options: nil)?[0] as! UITableViewCell as! EmojiTableViewCell
}
let emojiTitle = (haberler.object(at: indexPath.row) as AnyObject).value(forKey: "title") as! NSString as String
cell.emojiTitleLabel.text = emojiTitle.trimmingCharacters(in: .whitespaces)
cell.emojiImageView.downloadFrom(link: "http://teknolojix.net/wp-content/uploads/2014/10/Below-is-a-rendering-of-the-page-up-to-the-first-error-hatası.jpg", contentMode: UIViewContentMode.scaleAspectFill)
return cell
}

Your problem is very simple. you have pass the same link on the "downloadFrom" function. Please use "haberler" array to get the different image photo url. For example I used you above mentioned code to give you proper understanding.
CODE:
cell.emojiImageView.downloadFrom(link:haberler[indexPath.row].YOUR_PHOTO_URL_KEY_NAME, contentMode: UIViewContentMode.scaleAspectFill)
If you are not understand, please provide me "haberler" array so that I can give you proper solution with code.

Actually you are using hard-coded 'URL' to download image every time. You need to show image for every cell by getting different 'URL' from your data source same like you are getting 'title' for every cell. For example:
let emojiImageURL = (haberler.object(at: indexPath.row) as AnyObject).value(forKey: "url") as! NSString as String
cell.emojiImageView.downloadFrom(link: emojiImageURL, contentMode: UIViewContentMode.scaleAspectFill)

Related

Image repeates in every cell of table view in swift3

My JsonData -
let imagestring : String? = (myData as AnyObject).value(forKey: "Post_mid_image") as? String
if imagestring != nil {
let imageTrueString = "https://www.zdoof.com/" + imagestring!
self.imageStringArray.append(imageTrueString )
}
if let NameString = (myData as AnyObject).value(forKey: "Name") as? String {
self.nameStringArray.append(NameString)
}
When i am trying to set it to the table view cell
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.postLableArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reUse", for: indexPath)
let myImage = cell.viewWithTag(30) as! UIImageView
myImage.clipsToBounds = true
if indexPath.row < imageStringArray.count {
if let myImageString = imageStringArray[indexPath.row] as? String {
let ImageUrl = URL.init(string: myImageString)
myImage.kf.setImage(with: ImageUrl)
}
}
return cell
}
The image is repeating in every cell . Why it is happening ? Please help
As per the response you have given, you can show the image like below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dict = myData as AnyObject
let cell = tableView.dequeueReusableCell(withIdentifier: "reUse", for: indexPath)
let myImage = cell.viewWithTag(30) as! UIImageView
if dict["Post_mid_image"] != nil {
let imageUrl = URL.init(string: strImageUrl)
myImage.kf.setImage(with: imageUrl)
} else {
//Set placeholder image showing no image available
}
return cell
}
Problem is with cell re-usablity of table view here ,you have to handle it , you can have SDWebImage library for loading images in cell or you can have your own image cache which caches images with key/values , key as in image url , so dynamically checking image url for item at indexpath and load cached image with that image url as key.
Hope it helps!!
This is happening because of using tableView.dequeueReusableCell(withIdentifier: "reUse", for: indexPath).
Basically whenever you use dequeueReusableCell(withIdentifier:,For:), it will use the same cell for all of data. It means the total number of cell which are on screen are only going to load, for all other cell, it will use same cell with different value.
now consider a scenario that you are having 500 cells in tableview, but we can manage at most 10-15 cells in display, so for all other cells it will use same cells just modify the value of cell.
so what you can do here is, whenever you use if statement, don't forgot to add else too.
because for one scenario if cell's background is set to red, than we need to add else for another scenario, as cells are just repeated.

"Ambiguous reference to member 'count' " Error

I'm not that much of a pro in using swift..but i've been trying to create an social media app using firebase as backend. But I am stuck in this one part where the data gets stored in an Array..but when . i call the array I keep getting the "Ambiguous reference to member 'count' " error and I have tried many ways to fix this but end up unsuccessful every time
var posts = [AnyObject?]()
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: HomeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! HomeViewTableViewCell
let post = (posts[(self.posts.count - 1) - indexPath.row] as AnyObject).value["text"] as! String //**Ambiguous reference to member 'count'
cell.configure(nil,NameText:self.loggedInUserData!.value["NameText"] as! String, TitleText:self.loggedInUserData!.value["TitleText"] as! String, post:post)
return cell
}
Please help!
Actually trying this tutorial out in Youtube...So if full code required, This is the YouTube link:
https://www.youtube.com/watch?v=BeZ3i7-gaok&list=PLy9JCsy2u97kro0jXbXrPFmT-DQVAmNW0&index=4
you might want to use value(forKey:) here
let post = (posts[(self.posts.count - 1) - indexPath.row] as AnyObject).value(forKey: "text")

how can I get the image from dynamically generated UITableViewCell and pass it with segue to the other View?

I have a UITableViewController with UITableViewCell dynamically generated there. Each cell contains an imageView that I'm filling with images fetched from my server. I'm using alamofire_images to do so. My code looks as follows:
func tableView(testDetailsPanel: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = testDetailsPanel.dequeueReusableCellWithIdentifier("cell") as! TestDetailsCell
let test:SingleTest = self.items[indexPath.row] as! SingleTest
if(test.photo != "") {
cell.myPhoto.af_setImageWithURL(NSURL(string: test.photo)!)
} else {
cell.myPhoto.image = UIImage(named: "clusterLarge")
}
return cell
}
I thought that since I'm downloading images while displaying the table, there is no need to download it again on the other screen (which is accessible through clicking each cell).
So my idea was to pass the image from specific cell to the other screen through segue. But the problem is that from the method prepareForSegue I don't have access to the specific cell that user clicks. So my other choice was to use protocols. I created a very simple one:
protocol HandlePhoto: class {
func setUpBackgroundPhoto(miniature: UIImage)
}
and then in my native class I wanted to use it in didSelectRowAtIndexPath method:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let test:SingleTest = self.items[indexPath.row] as! SingleTest
let cell = testDetailsPanel.dequeueReusableCellWithIdentifier("cell") as! TestDetailsCell
if(test.photo != "") {
handlePhoto.setUpBackgroundPhoto(cell.testPhoto.image!)
self.performSegueWithIdentifier("testPhotoDetailsSegue", sender: test)
}
} else {
self.performSegueWithIdentifier("testTextDetailsSegue", sender: test)
}
}
But this line:
handlePhoto.setUpBackgroundPhoto(cell.testPhoto.image!)
throws error:
fatal error: unexpectedly found nil while unwrapping an Optional value
So my final question is: how can I access photo from the specific cell that user chooses and pass it to other view (without downloading it there for the 2nd time)?
Your didSelectRowAtIndexPath implementation is wrong, with dequeueReusableCellWithIdentifier you are obtaining a new cell, not the selected cell.
Try this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let selectedCell = tableView.cellForRow(at: indexPath) as! TestDetailsCell
//this will return downloaded image or "clusterLarge"
let image = selectedCell.myPhoto.image
//
//Make your check on image and extra setup
//
self.performSegueWithIdentifier("testPhotoDetailsSegue", sender: test)
}
Why are you using dequeueReusableCellWithIdentifier in your didSelectRowAtIndexPath?; instead, you should get the cell directly using:
let cell = yourTableView.cellForRowAtIndexPath(indexPath) as! TestDetailsCell
if let image = cell.testPhoto.image {
print(image)//this is what you want.
}

How to pass array to use SDImage to display image in swift

Here I am displaying images in imageView. I am able to display image but only single image in all rows of TableView I am using SDWebImage with swift for the first time. So I want to pass the array in the following code to display the respective images in each row.Here I am successfully displaying name by passing it through array now just wanted to display the images.
NOTE : see the code in comments below but its giving error want to pass the same array but don't know how to write in swift.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell
let strTitle : NSString = arrDict[indexPath.row].valueForKey("clip_name") as! NSString
cell.clipName.text = strTitle as String
cell.videoImage.sd_setImageWithURL(NSURL(string:"http://example.com/test/images/clips", arrDict(indexPath.r‌​ow).objectForKey("clip_image_path")))
return cell
}
You need to append your image name with your URL like this way.
let imagePath = String(format: "http://example.com/test/images/clips/%#",arrDict[indexPath.row].valueForKey("clip_image_path") as! NSString)
cell.videoImage.sd_setImageWithURL(NSURL(string: imagePath))

How to delete cache using HanekeSwift Swift?

I am stuck with a problem. I want to populate a tableview with some text and a profile image that can change i use this function for it.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CommonCellView!
cell = self.tableView.dequeueReusableCellWithIdentifier("CommonCellView") as! CommonCellView
cell.nameLabel.text = self.userCollection[indexPath.row].display_name
cell.companyLabel.text = self.userCollection[indexPath.row].user_organisation
cell.profileImage.hnk_setImageFromURL(NSURL(string: self.userCollection[indexPath.row].profile_picture)!)
self.makeImageViewCircular(cell.profileImage.layer, cornerRadius: cell.profileImage.frame.height)
cell.profileImage.clipsToBounds = true
return cell
}
nothing to suprising here. But when i change my own profile picture then i send it to the API and revist this function it shows the cached image. So i tought i might try something a bit diffent why not get all the images for every cell using Alamofire.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CommonCellView!
cell = self.tableView.dequeueReusableCellWithIdentifier("CommonCellView") as! CommonCellView
cell.nameLabel.text = self.userCollection[indexPath.row].display_name
cell.companyLabel.text = self.userCollection[indexPath.row].user_organisation
cell.profileImage.image = UIImage()
//getting the cell image
Alamofire.request(.GET, self.userCollection[indexPath.row].profile_picture)
.response {(request, response, avatarData, error) in
let img = UIImage(data: avatarData!)
cell.profileImage.image = img
}
self.makeImageViewCircular(cell.profileImage.layer, cornerRadius: cell.profileImage.frame.height)
cell.profileImage.clipsToBounds = true
return cell
}
this works to a point where user scrolles very fast the image of a different user will be shown until the request gets fulfilled. Okey so make that happen somewere else and use an array for the images. I also tried that. but because its async the images would go into the array in the wrong order. So back to HanekeSwift. I read the documentation and saw i had a cache on disk but i could not clear or delete it.
to clear the cache i also tried:
NSURLCache.sharedURLCache().removeAllCachedResponses()
but i did not do a thing. it works in the Alamofire situation but its not a good solution either.
I want to use hanekeSwift because HanekeSwift is fast enough to get all the images. but i want to clear the cache everytime the contoller loads.
Any suggestions would be appreciated!
Cees
I found a the problem.
First i was running an older version of the pod. So after updating i could use the function.
Shared.imageCache.removeAll()
after you import haneke into the controller.
the final pice of code looked like this.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CommonCellView!
cell = self.tableView.dequeueReusableCellWithIdentifier("CommonCellView") as! CommonCellView
cell.nameLabel.text = self.userCollection[indexPath.row].display_name
cell.companyLabel.text = self.userCollection[indexPath.row].user_organisation
cell.profileImage.image = UIImage()
//getting the cell image
cell.profileImage.hnk_setImageFromURL(NSURL(string: self.userCollection[indexPath.row].profile_picture)!)
//deleting it from cache
Shared.imageCache.removeAll()
self.makeImageViewCircular(cell.profileImage.layer, cornerRadius: cell.profileImage.frame.height)
cell.profileImage.clipsToBounds = true
return cell
}
it works now but removing the cache all the time an other cell gets filled seems a bit overkill.

Resources