Cannot retrieve image from Firebase into TableViewCell - ios

I just began to learn Firebase a week ago, but right now I am facing a problem of not able to load image from Firebase to my TableViewCell. I can retrieve data such as text information and the URL of the image from Firebase Realtime Database but not able to make use of those URL in order to fire up image on the TableViewCell. May you all help me identify the problems? I can retrieve everything such as text information as well as the image URL but how can I make the image pop up on the cell? All your help would be highly appreciate!
This is the ViewController that responsible to display the TableViewCell
import UIKit
import Firebase
import FirebaseStorage
class NewsFeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var rubthort:String = ""
var linkRub:String?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrItem.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! NewsFeed
// textlabel
// detailtextlabel
cell.textLabel?.text = arrItem[indexPath.row].name
cell.detailTextLabel?.text = arrItem[indexPath.row].price
//cell.imageView?.image = UIImage(named: "flower")
// Get image
let id = RetrieveData()
if let imageLink = self.linkRub {
let url = URL(string: imageLink)
//let data = NSData(contentsOf: url!)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
// download hit an error so return out
if error != nil {
print(error)
return
}
DispatchQueue.main.async {
cell.imageView?.image = UIImage(data: data!)
}
}.resume()
}
return cell
}
let ref = Database.database().reference()
// Array of PlasticItem
var arrItem = [RetrieveData]()
#IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
retrieveData()
} // Ends of viewDidLoad
func retrieveData() {
// Getting a node from database
let retRef = ref.child("item/electronic")
// Observing data changes
retRef.observe(DataEventType.value) { (dataSnapshot) in
// Remove array item everytime there is a new reference to the data in Firebase
self.arrItem.removeAll()
// Check if there are any children or second object inside the parent object
if dataSnapshot.childrenCount > 0 {
// Loop over all children's object
for post in dataSnapshot.children.allObjects as! [DataSnapshot] {
let object = post.value as! [String: Any]
let getName = object["name"] as! String
let getPrice = object["price"] as! String
let getImage = object["itemURL"] as! String
print(getName)
print(getPrice)
print(getImage)
self.linkRub = getImage
self.arrItem.append(RetrieveData(cat: "", name: getName, price: getPrice, rub: getImage))
}
self.tblView.reloadData()
}// Ends of if statement
else if dataSnapshot.childrenCount == 0{
print("No Data Found")
}
} // Ends of retRef.observe
} // Ends of retrieveData()
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
This is the model struct
import Foundation
import UIKit
struct RetrieveData{
var cat: String
var name: String
var price: String
var rub: String?
init(){
self.cat = ""
self.name = ""
self.price = ""
self.rub = ""
}
init(cat:String, name:String, price:String, rub: String){
self.cat = cat
self.name = name
self.price = price
self.rub = rub
}
}

Related

How to reload background UITableView from Modal View

I am trying to show an information which is in Core Data, on UITableViewCell.
I could get the information, but the information wasn't shown on UITableViewCell.
When I set the information on CoreData, I use Modal View then.
I tried to use UITableView.reload() but I couldn't show the information on UITableViewCell.
Please let me know how to show the information when I back from modal view.
This class is about showing the information on UItableView.
import UIKit
import CoreData
protocol FriendListTableViewDelegate {
func reloadTable()
}
class FriendListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FriendListTableViewDelegate{
#IBOutlet weak var friendListTableView: UITableView!
var friends:[FriendBasicInfo] = []
override func viewDidLoad() {
super.viewDidLoad()
getData()
}
// Disable to effect the reload
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadTable()
}
// fetch the information from CoreData
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
friends = try context.fetch(FriendBasicInfo.fetchRequest())
} catch {
print("error")
}
}
func reloadTable() {
friendListTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let friendCell = tableView.dequeueReusableCell(withIdentifier: "FriendListCell") as! FriendListTableViewCell
let friendName = friendCell.viewWithTag(1) as? UILabel
let friendImage = friendCell.viewWithTag(2) as? UIImageView
friendName?.text = friends[indexPath.row].name
friendImage?.image = friends[indexPath.row].photo?.toImage()
return friendCell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
This class is to get the information from CoreData
import UIKit
import XLPagerTabStrip
import Eureka
import CoreData
import ImageRow
class InputFriendInforViewController: FormViewController, IndicatorInfoProvider {
var itemInfo: IndicatorInfo = "Info"
var friendPhoto: UIImage?
var friendName: String = ""
var friendBirthday: Date?
var friendGender: String = ""
var friendListTableViewDelegate: FriendListTableViewDelegate!
override func viewDidLoad() {
super.viewDidLoad()
form +++
Section("Friend Information")
<<< ImageRow(){
$0.title = "Image"
$0.sourceTypes = [.PhotoLibrary, .SavedPhotosAlbum, .Camera]
$0.value = UIImage(named: "noImage")
$0.onChange { [unowned self] row in
self.friendPhoto = row.value!
}
}
<<< TextRow(){ row in
row.title = "Name"
row.placeholder = "Enter Name here"
}.onChange { name in
self.friendName = name.value!
}
<<< DateRow(){ row in
row.title = "Birthday"
row.value = Date(timeIntervalSinceReferenceDate: 0)
}.onChange {date in
self.friendBirthday = date.value!
}
<<< PushRow<String>(){row in
row.title = "Gender"
row.options = ["Male","Female","Other"]
}.onChange {gender in
self.friendGender = gender.value!
}
+++ Section()
<<< ButtonRow() {
$0.title = "SAVE"
}.onCellSelection {_, _ in
self.saveInfo()
}
}
// MARK: - IndicatorInfoProvider
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return itemInfo
}
// save friend Info for Core Data
func saveInfo (){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let friendEntity = NSEntityDescription.entity(forEntityName: "FriendBasicInfo", in: managedContext)!
let friendInfo = NSManagedObject(entity: friendEntity, insertInto: managedContext)
// make unique user ID
let friendUid = NSUUID().uuidString
// Image Data UIImage to png Data
let pngImage = self.friendPhoto?.toPNGData()
friendInfo.setValue(friendUid, forKey: "userID")
friendInfo.setValue(pngImage, forKey: "photo")
friendInfo.setValue(self.friendName, forKey: "name")
friendInfo.setValue(self.friendBirthday, forKey: "birthday")
friendInfo.setValue(self.friendGender, forKey: "gender")
do {
try managedContext.save()
self.dismiss(animated: true, completion:nil)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
This class is about UITableViewCell
import UIKit
class FriendListTableViewCell: UITableViewCell {
#IBOutlet weak var sampleImageView: UIImageView!
#IBOutlet weak var sampleLabel:UILabel!
}
V/r,
As you are using an extra data source array just reloading the table view doesn't consider the new inserted item.
There are a few options
Use NSFetchedResultsController. It updates the UI automatically when the context was saved.
On dismiss insert the new item into the data source array and a new row into the table view.
Observe NSManagedObjectContextDidSaveNotification and insert the item as described in 2.
Refetch the entire data and reload the table view.
The options are in order of efficiency. Version 1 is the most efficient one.
Side note:
viewWithTag is horribly old-fashioned. You got outlets, use them for example
cell.sampleLabel!.text = friends[indexPath.row].name
Your FriendListViewController TableView will reflect any updates to any FriendBasicInfo Entity which was fetched within getData() method. To present a new inserted FriendBasicInfo Entities to the database you have to execute a new fetch with getData() method.
Solution:
func reloadTable() {
getData()
friendListTableView.reloadData()
}
Alternative solution
Advanced monitoring of a fetched entities can be done with NSFetchedResultsController Delegate, this controller will automatically update the FriendListViewController tableview for any updated, inserted or deleted entities.

Passing data from Firebase Database from UITableviewCell to next ViewController not showing

I've already searched through some of the answers that have been asked about this but none of them seem to apply/work in my situation which is why I've decided to ask the community. I am simply trying to pass the data from the table view cell to the next view controller. I have gotten as far as being able to display the information in my cells accurately however whenever i select the row it just shows the view controller with no information
I have tried to set the labels and pictures to whatever the UITableViewCell may show but it is not working. I created an NSObject class that defines the variables which is why it is confusing me as to how to pass the data through to the next view Controller.
This is my AddFriendViewController where I fetch the users from Firebase and it displays my information on the tableview
class AddFriendViewController: UIViewController {
var users = [Users]()
var databaseRef = Database.database().reference()
#IBOutlet weak var friendsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
friendsTableView.delegate = self
friendsTableView.dataSource = self
fetchUser()
}
func fetchUser() {
databaseRef.child("users").observe(.childAdded) { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = Users()
user.nameOfUser = dictionary["nameOfUser"] as? String ?? ""
user.email = dictionary["email"] as? String ?? ""
user.profileImageURL = dictionary["profileImageURL"] as? String ?? ""
self.users.append(user)
DispatchQueue.main.async {
self.friendsTableView.reloadData()
}
}
}
}
}
extension AddFriendViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let friendCell = UITableViewCell(style: .subtitle, reuseIdentifier: "friendCell")
let user = users[indexPath.row]
friendCell.textLabel?.text = user.nameOfUser
friendCell.detailTextLabel?.text = user.email
if let profileImageURL = user.profileImageURL {
let url = URL(string: profileImageURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error)
return
}
DispatchQueue.main.async {
friendCell.imageView?.image = UIImage(data: data!)
}
}.resume()
}
return friendCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showFriendProfile", sender: self.users[indexPath.row])
self.friendsTableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showFriendProfile" {
if let indexPath = friendsTableView.indexPathForSelectedRow {
let dvc = segue.destination as! DetailViewController
***This is where I am confused as to what I should be doing***
//EDIT1:
print("The nameOfUser is \(user.nameOfUser!)")
print("The email is \(user.email!)")
}
}
}
}
This is my Users Class:
class Users: NSDictionary {
var nameOfUser: String?
var email: String?
var profileImageURL: String?
}
This is my DetailViewController:
class DetailViewController: UIViewController {
var nameOfUser = String()
var email = String()
var profileImageURL = UIImage()
var ref: DatabaseReference?
#IBOutlet weak var profileImageView: UIImageView!
#IBOutlet weak var nameOfUserLabel: UILabel!
#IBOutlet weak var emailLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
nameOfUser = nameOfUserLabel.text!
email = emailLabel.text!
profileImageURL = profileImageView.image!
}
}
The obvious goal is to simply click on the cell to show the data on the next view controller. I understand similar questions have been asked in the past but I truly don't know how to use those as the solution to my problem. Any help will be greatly appreciated and please let me know if there is anything I need to clarify.
EDIT1:
I added the print statement on the prepare for segue function and noticed it is at least pulling the information but for some reason not passing it to the next view controller.
Thank you
You just need to get your sender and set the properties of the detail view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showFriendProfile" {
guard let dvc = segue.destination as? DetailViewController else {
return
}
if let user = sender as? Users {
DispatchQueue.main.async {
dvc.nameOfUserLabel.text = user.nameOfUser
dvc.emailLabel.text = user.email
let url = URL(string: user.profileImageURL!)
let data = try? Data(contentsOf: url!)
dvc.profileImageView.image = UIImage(data: data!)
}
}
}
}
1- Send the object ( Make sure to connect the segue source to the vc itself not to the cell )
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showFriendProfile" {
if let indexPath = friendsTableView.indexPathForSelectedRow {
let dvc = segue.destination as! DetailViewController
dvc.user = sender as! Users
}
}
}
class DetailViewController: UIViewController {
var user:Users! // add this then inside viewDidLoad set the labels
}
2- Don't ise URLSession.shared.dataTask(with: url!) { (data, response, error) inside cellForRowAt consider using SDWebImage
import SDWebImage // install pods then add this line top of the vc
friendCell.imageView?.sd_setImage(with: URL(string:urlStr), placeholderImage: UIImage(named: "placeholder.png"))
3- No need for DispatchQueue.main.async { inside
DispatchQueue.main.async {
self.friendsTableView.reloadData()
}
As firebase callbacks run in main thread by default

Load images from API

I'm creating an e-commerce app with (Moltin.com) SDK, I set every thing well as it shown in the documentation but now I need to load multi images of single product in table view with custom cell, I set the shown code below and all I can get is a single image my app ignore load the other images view controller code is
class vc: UIViewController , UITableViewDelegate, UITableViewDataSource {
var productDict:NSDictionary?
#IBOutlet weak var tableview: UITableView!
fileprivate let MY_CELL_REUSE_IDENTIFIER = "MyCell"
fileprivate var productImages:NSArray?
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
Moltin.sharedInstance().product.listing(withParameters: productDict!.value(forKeyPath: "url.https") as! [String : Any]!, success: { (response) -> Void in
self.productImages = response?["result"] as? NSArray
self.tableview?.reloadData()
}) { (response, error) -> Void in
print("Something went wrong...")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if productImages != nil {
return productImages!.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MY_CELL_REUSE_IDENTIFIER, for: indexPath) as! MyCell
let row = (indexPath as NSIndexPath).row
let collectionDictionary = productImages?.object(at: row) as! NSDictionary
cell.setCollectionDictionary(collectionDictionary)
return cell
}
and my custom cell code is
class MyCell: UITableViewCell {
#IBOutlet weak var myImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setCollectionDictionary(_ dict: NSDictionary) {
// Set up the cell based on the values of the dictionary that we've been passed
// Extract image URL and set that too...
var imageUrl = ""
if let images = dict.value(forKey: "images") as? NSArray {
if (images.firstObject != nil) {
imageUrl = (images.firstObject as! NSDictionary).value(forKeyPath: "url.https") as! String
}
}
myImage?.sd_setImage(with: URL(string: imageUrl))
}
Can anyone show me where is the issue that doesn't let me get all the images of my product?
I'm using SWIFT 3, with XCode
In the code below you are always getting one URL from images array (firstObject).
if let images = dict.value(forKey: "images") as? NSArray {
if (images.firstObject != nil) {
imageUrl = (images.firstObject as! NSDictionary).value(forKeyPath: "url.https") as! String
}
}
myImage?.sd_setImage(with: URL(string: imageUrl))
If I understand correctly you should get every image in images array by the indexPath.row of your tableView.
For example add new parameter to method like this:
func setCollection(with dict: NSDictionary, and index: Int) {
// Set up the cell based on the values of the dictionary that we've been passed
// Extract image URL and set that too...
var imageUrlString = ""
if let images = dict.value(forKey: "images") as? Array<NSDictionary>, images.count >= index {
guard let lImageUrlString = images[index]["url.https"] else { return }
imageUrlString = lImageUrlString
}
guard let imageURL = URL(string: imageUrl) else { return }
myImage?.sd_setImage(with: imageURL)
}
Than when call this method in cellForRow just add indexPath.row to the second param.
But if you want show multiple images in one cell you should add more imageViews to the custom cell or use UICollectionView.
Just ping me if I don't understand you clear.

Read data from firebase and populate TableViewCell

Hello I have a tableviewcell where i can populate it with custom data from my pc, but i can't use my firebase data on the cell that i have made. I want to fill my cell with String and Int, not only Strings. My code is:
PlacesTableViewController Class
import UIKit
import FirebaseDatabase
class PlacesTableViewController: UITableViewController {
//MARK: Properties
#IBOutlet weak var placesTableView: UITableView!
//database reference
var dbRef:FIRDatabaseReference?
var places = [Places]()
var myList:[String] = []
//handler
var handle:FIRDatabaseHandle?
override func viewDidLoad() {
super.viewDidLoad()
dbRef = FIRDatabase.database().reference()
// Loads data to cell.
loadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return places.count
//return myList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "PlacesTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell else {
fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
}
let place = places[indexPath.row]
cell.placeLabel.text = place.name
cell.ratingControl.rating = place.rating
//cell.placeLabel.text = myList[indexPath.row]
//cell.ratingControl.rating = myRatings[indexPath.row]
return cell
}
//MARK: Private Methods
private func loadData() {
handle = dbRef?.child("placeLabel").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? String
{
self.myList.append(item)
self.placesTableView.reloadData()
print (item)
}
})
/* handle = dbRef?.child("rating").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? String
{
self.myList.append(item)
self.placesTableView.reloadData()
}
})*/
/*guard let place1 = Places(name: "Veranda", rating: 4) else {
fatalError("Unable to instantiate place1")
}
places += [place1]*/
}
}
Places Class
import UIKit
class Places {
//MARK: Properties
var name: String
var rating: Int
//MARK:Types
struct PropertyKey {
static let name = "name"
static let rating = "rating"
}
//MARK: Initialization
init?(name: String, rating: Int) {
// Initialize stored properties.
self.name = name
self.rating = rating
// Initialization should fail if there is no name or if the rating is negative.
// The name must not be empty
guard !name.isEmpty else {
return nil
}
// The rating must be between 0 and 5 inclusively
guard (rating >= 0) && (rating <= 5) else {
return nil
}
}
}
PlacesTableViewCell Class
import UIKit
import FirebaseDatabase
class PlacesTableViewCell: UITableViewCell, UITableViewDelegate {
//MARK: Properties
#IBOutlet weak var placeLabel: UILabel!
#IBOutlet weak var ratingControl: RatingControl!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Firebase Database
Assuming your database layout should instead look like this (see comments above):
...
placeLabel
|
-- XXY: "Veranda"
-- YYY: "Dio Con Dio"
rating
|
-- XXX: 4
-- YYY: 1
...
then try this:
private func loadData() {
dbRef!.child("placeLabel").observe(.childAdded) {
(snapshot) in
let label = snapshot.value as! String
self.updatePlace(snapshot.key, label: label)
}
dbRef!.child("rating").observe(.childAdded) {
(snapshot) in
let rating = snapshot.value as! Int
self.updatePlace(snapshot.key, rating: rating)
}
}
private var loadedLabels = [String: String]()
private var loadedRatings = [String: Int]()
private func updatePlace(_ key: String, label: String? = nil, rating: Int? = nil) {
if let label = label {
loadedLabels[key] = label
}
if let rating = rating {
loadedRatings[key] = rating
}
guard let label = loadedLabels[key], let rating = loadedRatings[key] else {
return
}
if let place = Places(name: label, rating: rating) {
places.append(place)
placesTableView.reloadData()
}
}
By the way, you can temporarily hack your database — using Firebase (nice!) web console — if you want to quickly validate the above solution.
Writing to Database. Try the following code to write the nodes in your database (i.e., this code reuses the same key across all place properties):
let key = dbRef!.child("placeLabel").childByAutoId().key
dbRef!.child("placeLabel").child(key).setValue(placeLab‌​el.text)
dbRef!.child("comment").child(key).setValue(commentText‌​Field.text)
dbRef!.child("rating").child(key).setValue(ratingContro‌​l.rating)
Hacking the Database. To edit the database manually, try:
open http://console.firebase.google.com
select your app
open database option
add a new node with the right key
delete the old node

Text not fully passed after prepareForSegue (swift 3)

So I built an app which loads the news into the tableView cells.
Now I want the user to be able to open individual article.
To do that I passed the selected cells using prepareForSegue method and it works but partially.
It passes the title and image properly but the full text is shown partially, to be precise it is shown as in the cells.
Here is my table of news class:
import Alamofire //Framework for handling http requests
import UIKit
import AlamofireImage
class NewsTableViewController: UITableViewController {
//Custom struct for the data
struct News {
let title : String
let text : String
let link : String
let imgUrl : String
init(dictionary: [String:String]) {
self.title = dictionary["title"] ?? ""
self.text = dictionary["text"] ?? ""
self.link = dictionary["link"] ?? ""
self.imgUrl = dictionary["imgUri"] ?? ""
}
}
//Array which holds the news
var newsData = [News]()
// Download the news
func downloadData() {
Alamofire.request("https://api.sis.kemoke.net/news").responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // HTTP URL response
print(response.data as Any) // server data
print(response.result) // result of response serialization
//Optional binding to handle exceptions
self.newsData.removeAll() // clean the data source array
if let json = response.result.value as? [[String:String]] {
for news in json {
self.newsData.append(News(dictionary: news))
}
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
downloadData()
tableView.rowHeight = 100
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? newsCellTableViewCell
let news = newsData[indexPath.row]
cell?.headline.text = news.title
Alamofire.request(news.imgUrl).responseImage { response in
debugPrint(response)
print(response.request as Any)
print(response.response as Any)
debugPrint(response.result)
let cellImage = response.result.value
if let image = response.result.value {
print("image downloaded: \(image)")
}
cell?.thumbnailImage.image = cellImage
}
print(news.imgUrl)
return cell!
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showArticle" {
let nextScene = segue.destination as! ArticleViewController
// Pass the selected object to the new view controller.
if let indexPath = self.tableView.indexPathForSelectedRow {
let selectedCells = newsData[indexPath.row]
nextScene.articleTitleString = selectedCells.title
nextScene.receiveFullText = selectedCells.title
//Downloading an image to be displayed in a single article
Alamofire.request(selectedCells.imgUrl).responseImage { response in
debugPrint(response)
print(response.request as Any)
print(response.response as Any)
debugPrint(response.result)
let cellImage = response.result.value
nextScene.articleImage.image = cellImage!
}
}
}
}
}
And here is my destination view controller for the single article in which I am passing the information
class ArticleViewController: UIViewController {
#IBOutlet weak var articleTitle: UILabel!
var articleTitleString = ""
#IBOutlet weak var articleImage: UIImageView!
#IBOutlet weak var fullText: UITextView!
var receiveFullText = ""
override func viewWillAppear(_ animated: Bool) {
articleTitle.text = articleTitleString
fullText.text = receiveFullText
}
}
And this is what happens
http://imgur.com/2GQddeW
http://imgur.com/jos3VhE
See? The full text is not shown even though the server is returning full text.
I did test this by creating a textView in another view controller and get the text from the server and it worked fine.
The issue looks like it's copying a layout of the label in the cell and displaying what is in that label.
Also a tried putting another label in to the cell to load the text init and it worked properly, than after tapping a cell it displayed what was in that label.
What I want is to load a full text when this segue happens.
nextScene.articleTitleString = selectedCells.title
nextScene.receiveFullText = selectedCells.title
You are passing the title twice instead of the full text...

Resources