load images made slow my tableview - ios

I got my data from a json url, but when I want to load my images, it is very slowly !
class NewsTableViewController: UITableViewController {
var ids = [String]()
var titles = [String]()
var descriptions = [String]()
var images = [String]()
var links = [String]()
var dates = [String]()
#IBOutlet var table_news: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table_news.delegate = self
getNews()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.ids.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:NewsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "news_cell") as! NewsTableViewCell
cell.lbl_date.text = self.dates[indexPath.row]
cell.lbl_title.text = self.titles[indexPath.row]
var des = self.descriptions[indexPath.row]
if des.characters.count > 200 {
let range = des.rangeOfComposedCharacterSequences(for: des.startIndex..<des.index(des.startIndex, offsetBy: 200))
let tmpValue = des.substring(with: range).appending("...")
cell.lbl_des.text = tmpValue
}
DispatchQueue.main.async{
cell.img_news.setImageFromURl(stringImageUrl: self.images[indexPath.row])
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func getNews() {
RestApiManager.sharedInstance.getNews { (json: JSON) in
if let results = json.array {
for entry in results {
self.ids.append(entry["id"].string!)
self.titles.append(entry["title"].string!)
self.descriptions.append(entry["description"].string!)
self.images.append(entry["images"].string!)
self.links.append(entry["link"].string!)
self.dates.append(entry["date"].string!)
}
DispatchQueue.main.async{
self.table_news.reloadData()
}
}
}
}
}
custom cell:
extension UIImageView{
func setImageFromURl(stringImageUrl url: String){
if let url = NSURL(string: url) {
if let data = NSData(contentsOf: url as URL) {
self.image = UIImage(data: data as Data)
}
}
}
}
class NewsTableViewCell: UITableViewCell {
#IBOutlet weak var img_news: UIImageView!
#IBOutlet weak var lbl_title: UILabel!
#IBOutlet weak var lbl_date: UILabel!
#IBOutlet weak var lbl_des: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
lbl_des.lineBreakMode = .byWordWrapping // or NSLineBreakMode.ByWordWrapping
lbl_des.numberOfLines = 0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I'm using an extension image view.

The problem for the slowness you are mentioning are in the UIImageView extension
extension UIImageView{
func setImageFromURl(stringImageUrl url: String){
if let url = NSURL(string: url) {
if let data = NSData(contentsOf: url as URL) {
self.image = UIImage(data: data as Data)
}
}
}
}
In the NSData(contentsOf: url as URL) you are retrieving the contents of the URL synchronously from the network, blocking the main thread. You can download the content using a NSURLSession with an asynchronous callback or using some 3rd party libraries (SDWebImage probably being the most used and battle tested).

Related

Send data from detail view controller to table view controller

I create an app which uses https://newsapi.org/.
There is a table view that contains news and they have their detail page (Detail View Controller).
Detail view controller has a tab bar button item which is favorites button(<3).
This button send data to favorites table view. But can't send data. Also, in favorites table view you can click the cell and go detail view controller again. So there is two way. And i want to go BACK segue.
main.storyboard:
this is NewsTableViewController:
import UIKit
import Alamofire
class NewsTableViewController: UITableViewController , UISearchBarDelegate {
#IBOutlet weak var searchBar: UISearchBar!
var arr : [Article]? = []
var filteredData: [Article] = []
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
//
// let parameters = ["q":"%20", "page": "1", "apiKey":"06c2318ea4c64504b48b3d126168203c"]
let parameters = ["q":"saliha", "page": "1", "apiKey":"06c2318ea4c64504b48b3d126168203c"]
let url = "https://newsapi.org/v2/everything"
AF.request(url, method: .get, parameters: parameters) .responseJSON { (res) in
if(res.response?.statusCode == 200) {
print("res data: ",res.data as Any)
let news = try? JSONDecoder().decode(News.self, from: res.data!)
self.arr = news?.articles
self.tableView.reloadData()
print("kaç sonuç var?",news?.totalResults as Any)
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(filteredData.count > 0) {
return filteredData.count
} else {
return arr!.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NewsTableViewCell
let item: Article
if filteredData.count > 0 {
item = filteredData[indexPath.row]
} else {
item = arr![indexPath.row]
}
DispatchQueue.main.async {
let url = URL(string: item.urlToImage!)
let data = try! Data(contentsOf: url!)
cell.newsImage.image = UIImage(data: data)
}
cell.newsTitle.text = item.title
cell.newsAbout.text = item.description
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sender: Article
if filteredData.count > 0 {
sender = filteredData[indexPath.row]
}
else {
sender = arr![indexPath.row]
}
performSegue(withIdentifier: "detail", sender: sender)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if ( segue.identifier == "detail" ) {
let vc = segue.destination as! DetailViewController
vc.item = (sender as! Article)
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = []
if searchText == ""{
filteredData = arr!
}
else{
for item in arr!{
if item.title!.lowercased().contains(searchText.lowercased()){
filteredData.append(item)
}
}
}
self.tableView.reloadData()
}
}
this is DetailViewController:
import UIKit
import Alamofire
class DetailViewController: UIViewController {
var item: Article!
var arr: [Article] = []
var favArr: [Article] = []
#IBOutlet weak var dTitle: UILabel!
#IBOutlet weak var dImage: UIImageView!
#IBOutlet weak var dDate: UILabel!
#IBOutlet weak var dAbout: UITextView!
#IBAction func btnWebview(_ sender: Any) {
performSegue(withIdentifier: "goWeb", sender: item)
}
#IBAction func btnFav(_ sender: UIBarButtonItem) {
print("favoriler ekleme butonuna basıldı")
}
#IBAction func btnShare(_ sender: UIBarButtonItem) {
let items = [URL(string: item.url!)]
let ac = UIActivityViewController(activityItems: items as [Any], applicationActivities: nil)
present(ac, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: item.urlToImage!)
let data = try! Data(contentsOf: url!)
dImage.image = UIImage(data: data)
dTitle.text = item.title
dAbout.text = item.description
dDate.text = item.publishedAt
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if ( segue.identifier == "goWeb" ) {
let vc = segue.destination as! WebViewViewController
vc.item = (sender as! Article)
}
}
}
this is FavoriteTableViewController:
import UIKit
import Alamofire
class FavoriteTableViewController: UITableViewController {
var item: Article!
var arr : [Article]? = []
var favArr: [Article] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return favArr.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "favcell", for: indexPath) as! FavoriteTableViewCell
let url = URL(string: item.urlToImage!)
let data = try! Data(contentsOf: url!)
cell.fImage.image = UIImage(data: data)
cell.fTitle.text = item.title
cell.fDetail.text = item.description
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "detail", sender: item)
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}

When adding a text using UITextField from another controller it doesn't show up in the UITableView

I have to create a Web app. I use Split View. In my main view I have and Add button, where I enter the name of the page and its URL, after I press save and it should show up in the UITableView as a new row. All the buttons work, but new row doesn't appear. I'm not sure why.
Here is my main UITableView
import UIKit
import WebKit class WebBrowsers: UITableViewController, NewDelegate {
private var list:[List] = [
List(name: "google", url: URL(string: "https://google.com")),
List(name: "facebook", url: URL(string: "https://www.facebook.com"))
]
#IBOutlet weak var myTableView: UITableView!
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
let addContactVC = storyboard?.instantiateViewController(identifier: "AddBrowser") as! AddBrowser
addContactVC.delegate = self
navigationController?.pushViewController(addContactVC, animated: true)
addContactVC.modalPresentationStyle = .fullScreen
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Browsers"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = list[indexPath.row].name
// Configure the cell...
return cell
}
func addSomeCell(name: String?, url:URL!){
let listNew = List.init(name: name,url: url)
self.list.append(listNew)
myTableView.reloadData()
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
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.
if segue.identifier == "showDetail"{
if let navcon = segue.destination as? UINavigationController{
if let destination = navcon.visibleViewController as? infoBrowser{
if let row = tableView.indexPathForSelectedRow?.row{
destination.detailUrl = list[row].url
destination.navigationItem.title = list[row].name
}
}
}
}
}
}
public protocol NewDelegate: class{
func addSomeCell(name: String?, url:URL!)}
here is my AddButton ViewController
import UIKit
class AddBrowser: UIViewController {
var delegate: NewDelegate?
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var urlTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func saveButtonPressed(_ sender: UIButton) {
self.delegate?.addSomeCell(name: nameTextField.text!, url: URL(string: urlTextField.text!))
navigationController?.popViewController(animated: true)
}
/*
// 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.
} }

Retrieving firebase children and populating them in a UITableView

Trying to query firebase children and retrieve a snapshot array of their data into a tableview. Not sure if I am implementing this correctly, but I am not the getting a runtime error. However, my tableview is just white with no objects displaying. Some feedback would be helpful. Thanks.
Here is my FB JSON tree structure
Here is my User class (var userList = User)
class CDetailTableViewController: UITableViewController {
static var imageCache = NSCache<AnyObject, UIImage>()
var userList = [User]()
var ref = FIREBASE.FBDataReference().ref
var refHandle: UInt!
override func viewDidLoad() {
super.viewDidLoad()
ref = FIREBASE.FBLink().FBref
configureCell()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CDetailTableViewCell
cell.priceLabel?.text = userList[indexPath.row].priceLabel
cell.titleLabel?.text = userList[indexPath.row].titleLabel
cell.itemPhoto?.image = userList[indexPath.row].objectImage
return cell
}
func configureCell(){
let ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
refHandle = ref.child("Enterpriser Listings").child("Sell Old Stuff - Listings").child(userID!).observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
print("get dictionary")
print(dictionary)
let user = User()
user.setValuesForKeys(dictionary)
self.userList.append(user)
// Get user value
DispatchQueue.main.async {
print("reloaded")
self.tableView.reloadData()
}
}
})
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
May be the problem is with your Firebase reference, try like this way.
ref.child("Enterpriser Listings").child("Sell Old Stuff - Listings").observe(.value, with: { (snapshot:FIRDataSnapshot) in
var users = [User]()
for child in snapshot.children {
print("\((sweet as! FIRDataSnapshot).value)")
if let dictionary = child.value as? [String : AnyObject] {
let user = User()
user.setValuesForKeys(dictionary)
users.append(user)
}
}
self.userList = users
self.tableView.reloadData()
})
Simple question. Have you delegated your tableview?
class YourController: < other >, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() { //for example this function
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}

Unrecognized selector sent to instance when display pictures

I have the following code//
// doctorsList.swift
// iLegaltwo
//
// Created by Bharath on 10/1/16.
// Copyright © 2016 Bharath. All rights reserved.
//
import UIKit
import Parse
class doctorsList: UITableViewController {
#IBOutlet var doctorsListTableView: UITableView!
var profImages = [PFFile]()
var doctorName = [String]()
var doctorRate = [NSDecimal]()
var doctorPracArea = [String]()
var doctorExp = [String]()
var refresher: UIRefreshControl!
func refresh()
{
let query = PFQuery(className: "doctors_Directory")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock(
{
(listll: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(listll!.count) names of the doctors.")
// Do something with the found objects
if let objects = listll {
for object in objects {
print(object)
self.profImages.append(object["ProfileImage"] as! PFFile)
self.doctorName.append(object["doctor_Name"] as! String)
self.doctorExp.append(object["Exp"] as! String)
self.doctorPracArea.append(object["Practice_Area"] as! String)
// print(object["doctor_Name"] as! String )
// self.doctorsname.append(object["doctor_Name"] as! String)
//self.lblName.text = object["doctor_Name"] as? String
}
self.doctorsListTableView.reloadData()
}
print(self.doctorName.count)
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
self.tableView.reloadData()
self.refresher.endRefreshing()
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refrehsh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return doctorName.count
//return 6
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let doctorcell: doctorsListCell = tableView.dequeueReusableCellWithIdentifier("doctorlistproto") as! doctorsListCell
doctorcell.lblNamell.text = doctorName[indexPath.row]
doctorcell.lblExpll.text = doctorExp[indexPath.row]
doctorcell.lblPracareall.text = doctorPracArea[indexPath.row]
profImages[indexPath.row].getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
if imageData != nil {
let image = UIImage(data: imageData!)
doctorcell.imagedoctor.image = image
}
else
{
print(error)
} }
//cell.textLabel?.text = doctorsname[indexPath.row]
return doctorcell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
EDIT
doctorListCell class
import UIKit
class doctorsListCell: UITableViewCell {
#IBOutlet var imagedoctor: UIImageView!
#IBOutlet var lblNamell: UILabel!
#IBOutlet var lblRatell: UILabel!
#IBOutlet var lblExpll: UILabel!
#IBOutlet var lblPracareall: UILabel!
}
No issues when I build, but not able to display profileImages, this is the error I get in the output window
2016-01-24 00:42:33.275 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8ee6760
2016-01-24 00:42:33.276 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8e87670
2016-01-24 00:42:33.276 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8ed3540
2016-01-24 00:42:33.277 iLegaltwo[12534:831589] -[UITableViewCellContentView setImage:]: unrecognized selector sent to instance 0x7ffab8ed2420
-[UITableViewCellContentView setImage:]: unrecognized selector sent to instance
That's saying that you're trying to do a setImage: on a UITableViewCellContentView object (which doesn't have this method), and not on a UIImageView (imageDoctor) as you wrote it:
doctorcell.imagedoctor.image = image
So my guess, which seems to be the reason is that you linked imageDoctor (IBOutlet) to the contentView of doctorsListCell instead of the UIImageView.

delegate modal view swift

I have tried the other methods for delegation and protocols for passing data between modal views and the parent view button they aren't working for me. This is obviously because I am implementing them wrong.
What I have is a parent view controller which has a tableviewcell which in the right detail will tell you your selection from the modal view. The modal view is another table view which allows you to select a cell, which updates the right detail and dismisses the modal view. All is working except the actual data transfer.
Thanks in advance!! :)
Here is my code for the parent view controller:
class TableViewController: UITableViewController, UITextFieldDelegate {
//Properties
var delegate: transferData?
//Outlets
#IBOutlet var productLabel: UILabel!
#IBOutlet var rightDetail: UILabel!
override func viewWillAppear(animated: Bool) {
println(delegate?.productCarrier)
println(delegate?.priceCarrier)
if delegate?.productCarrier != "" {
rightDetail.text = delegate?.productCarrier
productLabel.text = delegate?.productCarrier
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 5
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 1
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
The code for the model view controller and protocol is:
protocol transferData {
var priceCarrier: Double { get set }
var productCarrier: String { get set }
}
class ProductsDetailsViewController: UITableViewController, transferData {
//Properties
var priceCarrier = 00.00
var productCarrier = ""
//Outlets
//Actions
#IBAction func unwindToViewController(segue: UIStoryboardSegue) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
populateDefaultCategories()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return Int(Category.allObjects().count)
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return (Category.allObjects()[UInt(section)] as Category).name
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return Int(objectsForSection(section).count)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:ProductListCell = tableView.dequeueReusableCellWithIdentifier("productCell", forIndexPath: indexPath) as ProductListCell
let queriedProductResult = objectForProductFromSection(indexPath.section, indexPath.row)
cell.name.text = queriedProductResult.name
cell.prices.text = "$\(queriedProductResult.price)"
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow()!
let product = objectForProductFromSection(indexPath.section, indexPath.row)
let PVC: TableViewController = TableViewController()
println("didSelect")
productCarrier = product.name
priceCarrier = product.price
println(productCarrier)
println(priceCarrier)
self.dismissViewControllerAnimated(true, completion: nil)
}
I think for passing data, you should use segue like:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow()!
let product = objectForProductFromSection(indexPath.section, indexPath.row)
println("didSelect")
productCarrier = product.name
priceCarrier = product.price
println(productCarrier)
println(priceCarrier)
self.performSegueWithIdentifier("displayYourTableViewControllerSegue", sender: self)
}
and then override the prepareForSegue function:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var controller = segue.destinationViewController as TableViewController
controller.rightDetail.text = "\(self.priceCarrier)"
controller.productLabel.text = self.productCarrier
}

Resources