I have a create a xib as customTableViewCell and on my main storyboard, I have a ViewController as a popUp and have link the viewController to the popUp through a segue way. Now I am trying to open the popUp through didSelectRowAt. When I run the app and click on a row it gives error
<CustomTableCell.ViewController: 0x7feb4650ea00>) has no segue with identifier 'popUp'
Below is my code
import UIKit
import os.log
class ViewController: UITableViewController {
var data = [Response.Recipe]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Restaurants"
downloadJson()
tableView.delegate = self
tableView.dataSource = self
//tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
let nib = UINib(nibName: "viewTblCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "customCell")
if #available(iOS 10.0, *) {
tableView.refreshControl = refresher
} else {
tableView.addSubview(refresher)
}
// sampleData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: CustomTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as? CustomTableViewCell else {
os_log("Dequeue cell isn't an instance of CustomTableCell", log: .default, type: .debug)
fatalError()
}
cell.recipeNameLbl?.text = data[indexPath.row].recipeName
let image = data[indexPath.row].recipeImage
let ImageUrl = "http://localhost:8888/restaurant/recipeImages/"+image
if let imageURL = URL(string: ImageUrl) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.recipeImg?.image = image
}
}
}
}
let restaurantOpen = data[indexPath.row].restaurantStatus
if restaurantOpen == "Closed" {
cell.restaurantStatusLbl?.text = restaurantOpen
cell.restaurantStatusLbl?.isHidden = false
}else{
cell.restaurantStatusLbl?.isHidden = true
}
cell.restaurantOperateDays?.text = data[indexPath.row].restaurantOpenDays
cell.restaurantOperateTime?.text = data[indexPath.row].restaurantOpenTime
cell.retaurantNameLbl?.text = data[indexPath.row].restaurantName
cell.recipeTimeLbl?.text = "Delivers in " + String(describing: data[indexPath.row].recipeTime) + " minutes"
cell.recipePriceLbl?.text = "GHS " + String(describing: data[indexPath.row].recipePrice)
//cell.delegate = self
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "popUp", sender: self)
print(data[indexPath.row].recipeName)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? AddToCartViewController {
destination.popUpDetails = data[(tableView.indexPathForSelectedRow?.row)!]
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 230
}
func downloadJson() {
let url = URL(string: "http://localhost:8888/restaurant/tableView.php")
guard let downloadURL = url else { return }
URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong")
return
}
print("downloaded")
do
{
let decoder = JSONDecoder()
let downloadedRecipes = try decoder.decode(Response.self, from: data)
self.data = downloadedRecipes.recipeTbl
print(downloadedRecipes.recipeTbl)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}.resume()
}
lazy var refresher: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.tintColor = UIColor.red
refreshControl.addTarget(self, action: #selector(requestData), for: .valueChanged)
return refreshControl
}()
#objc func requestData(){
let deadline = DispatchTime.now() + .milliseconds(800)
DispatchQueue.main.asyncAfter(deadline: deadline){
self.downloadJson()
self.refresher.endRefreshing()
}
}
}
I finally achieved what I wanted to do
I move the popUp to its own storyboard then gave it Storyboard ID "addToCart"
Then I open it in the didSelectRowat method
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let popup = UIStoryboard(name: "AddToCart", bundle: nil)
let addToCartPopup = popup.instantiateInitialViewController()! as! AddToCartViewController
addToCartPopup.popUpDetails = data[(tableView.indexPathForSelectedRow?.row)!]
self.present(addToCartPopup, animated: true)
}
Related
I am not able to display the JSON data in my table view. I don't know why. I tried to get the JSON data, but I am not able to display it on screen in a table format.
This is the model:
class PastTripsVC: UIViewController {
var past = [PastRide]()
#IBOutlet weak var mTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let nibCell = UINib(nibName: "PastTableView", bundle: nil)
mTable.register(nibCell, forCellReuseIdentifier: "cell")
apiCalling()
}
func apiCalling(){
if let url = URL(string: "https://pincood.com/pincood/public/api/user/trips") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = [
"Content-Type": "application/json",
"Session": "fb4e7f9b-0f31-4709-",
"AUthorization":"<some key>"
]
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { return }
guard let data = data else { return }
do{
let codabledata = try JSONDecoder().decode([PastRide].self, from: data)
print(codabledata)
DispatchQueue.main.async {
self.past = codabledata
self.mTable.reloadData()
}
} catch {
print(error)
}
}.resume()
}
}
In the extension we try:
extension PastTripsVC : UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return past.count
print(past.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PastTableView
cell.usernm.text = past[indexPath.row].provider.firstName
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let details : PastDetailView = self.storyboard?.instantiateViewController(withIdentifier: "PastDetailView") as! PastDetailView
navigationController?.pushViewController(details, animated: true)
}
}
You need to set table view's delegate and datasource properties in viewDidLoad.
Update your viewDidLoad to look like this:
override func viewDidLoad() {
super.viewDidLoad()
let nibCell = UINib(nibName: "PastTableView", bundle: nil)
mTable.register(nibCell, forCellReuseIdentifier: "cell")
mTable.delegate = self
mTable.datasource = self
apiCalling()
}
I'm trying to pass data from a news Api to a tableView, but I'm having an issue, the data is returning nil when it get's pass to the SectorNewsVC, And by the time it gets to the infoVC it's still nil, however when I print the data before it gets pass it there. Can someone explain what I am doing wrong and, how I can go about fixing it? Thank You!!
This is where I'm creating the URLSession and fetching the data, and attempting to pass the data over to the Viewcontroller which is calling the fetchSectorNews() to retrive the data from an API.
struct FetchCategoryResponse {
let sectorUrl = "https://stocknewsapi.com/api/v1/category?section=alltickers&items=50&type=article&token=\(Key.api_key)"
func fetchSectorNews(sector: String) {
let urlString = "\(sectorUrl)§or=\(sector)"
performRequest(urlString: urlString)
print(urlString)
}
func performRequest(urlString: String) {
// create url
if let url = URL(string: urlString) {
// create url session
let session = URLSession(configuration: .default)
// give session a task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
if let news = self.parseJson(sectorData: safeData) {
DispatchQueue.main.async {
let vc = SectorNewsVC()
vc.dataToPass = news
}
}
}
}
task.resume()
}
}
// parse the jason data
func parseJson(sectorData: Data) -> SectorModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(CatergoryData.self, from: sectorData)
let newsUrl = decodedData.data[1].title
let imageUrl = decodedData.data[1].news_url
let title = decodedData.data[1].title
let source = decodedData.data[1].source_name
let sectorPayload = SectorModel(url: newsUrl, image: imageUrl, title: title, source: source)
// this sectorpayload gets saved to the news var in the performrequest() bc its being return
return sectorPayload
}
catch {
print(error)
return nil
}
}
} // END Struct
so in this ViewController I'm setting up the collectionViewController and calling the fetchSectorNews() and passing in the title of the label as the argunemt for the function, while trying to pass the data over to the detialViewController
var titleArr = ["Technology", "Materials", "HealthCare"]
var dataToPass: SectorModel?
var fetchNews = FetchCategoryResponse()
extension SectorNewsVC: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return titleArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! SectorCollectionCell
cell.listLabel.text = titleArr[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let curentIndex = indexPath.item
if curentIndex == 0 {
fetchNews.fetchSectorNews(sector: "technology")
}
else if curentIndex == 1 {
fetchNews.fetchSectorNews(sector: "materials")
}
else if curentIndex == 2 {
fetchNews.fetchSectorNews(sector: "healthcare")
}
performSegue(withIdentifier: "segue", sender: nil)
} // end cv()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
if let indexPath = self.collectionView.indexPathsForSelectedItems {
let detailVC = segue.destination as! infoVC
detailVC.newData = dataToPass
print(indexPath)
}
}
}
}
Here is where I want to display the data
class infoVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var newData: SectorModel?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.showsVerticalScrollIndicator = false
tableView.backgroundColor = #colorLiteral(red: 0.1926331222, green: 0.2233074605, blue: 0.3540094197, alpha: 1)
tableView.register(UINib(nibName: "DifferentSectorCell", bundle: nil), forCellReuseIdentifier: "cellId")
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("tap")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! DifferentSectorCell
cell.titleLabel.text = "hey"
cell.sourceLabel.text = "hello"
return cell
}
}
I would suggest a different approach. Sending the section to the child controller, and do the request on the child. Here is what has worked for me before
on the parent controller:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let curentIndex = indexPath.item
var sector = ""
if curentIndex == 0 {
sector = "technology"
}
else if curentIndex == 1 {
sector = "materials"
}
else if curentIndex == 2 {
sector = "healthcare"
}
performSegue(withIdentifier: "segue", sender: sector)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let detailVC = segue.destination as! infoVC
detailVC.sector = sender as! String
}
}
}
on the child controller:
var sector = ""
override func viewWillAppear() {
super.viewWillAppear()
fetchNews.fetchSectorNews(sector: self.sector)
}
I have a ViewController, where a list of data is being fetched from the RealtimeDatabase and being displayed in the UITableView. When a post is clicked, I want the data from the ViewController such as Title, Description, and Image to be carried forward into a DetailView i.e: PostController.Swift where I can further call more data from the RealtimeDatabase to be displayed in the PostController.Swift
I tried to use didSelectRowAt but was unable to fetch and display data in the PostController, I'm also currently trying to use prepare but getting stuck at the same place.
Here is the ViewController.Swift:
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView:UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView(frame: view.bounds, style: .plain)
view.addSubview(tableView)
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
var layoutGuide:UILayoutGuide!
layoutGuide = view.safeAreaLayoutGuide
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.reloadData()
observePosts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func observePosts() {
let postsRef = Database.database().reference().child("Data")
postsRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children{
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let title = dict["title"] as? String,
let logoImage = dict["image"] as? String,
let url = URL(string:logoImage),
let description = dict["description"] as? String{
let userProfile = UserProfile(title: title, photoURL: url)
let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile)
print(post)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableView.reloadData()
})
}
func getImage(url: String, completion: #escaping (UIImage?) -> ()) {
URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
if error == nil {
completion(UIImage(data: data!))
} else {
completion(nil)
}
}.resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
tableView.estimatedRowHeight = 50
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PostDetailSegue" {
if let indexPaths = self.tableView!.indexPathForSelectedRow{
}
}
}
}
You need to store a reference to the Post in your DetailViewController.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PostDetailSegue" {
let detailViewController = segue.destinationViewController as! DetailViewController
let indexPath = tableView.indexPathForSelectedRow
let post = posts[indexPath.row]
detailViewController.setPost(post)
}
}
And in your DetailViewController:
func detailViewController.setPost(_ post: Post) {
// Store the post and fetch other data as necessary
self.post = post
}
try this one.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let postsInfo = posts[indexPath.row]
print(postsInfo)
performSegueWithIdentifier("PostDetailSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PostDetailSegue" {
if let indexPaths = posts[indexPath.row]{
//add parmaters which passed to another viewcontroller
}
}
}
I have a TabBar with various Tabs in my RestaurantApp, When I click the addToCart and goes to the CartViewContorller, the added item don't show I have to relaunch the App to see the item there. I have seen similar questions with various answer on this question here but non of the solutions seems to work in my case I don't really know whats wrong. Below is my code for the CartViewContorller I want to reload tableview anytime it is loaded. Thanks all for your help
import UIKit
import Alamofire
import os.log
class CartViewController: UITableViewController {
var cartData = [CartResponse.Cart]()
override func viewDidLoad() {
super.viewDidLoad()
cart()
tableView.delegate = self
tableView.dataSource = self
let nib = UINib(nibName: "viewCartCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "cartCustomCell")
let footerView = UIView()
footerView.backgroundColor = UIColor.red
footerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 60)
tableView.tableFooterView = footerView
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cartData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: CartTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cartCustomCell", for: indexPath) as? CartTableViewCell else {
os_log("Dequeue cell isn't an instance of CustomTableCell", log: .default, type: .debug)
fatalError()
}
cell.recipeNameLbl?.text = cartData[indexPath.row].recipeName
cell.restaurantNameLbl?.text = cartData[indexPath.row].restaurantName
cell.addtionalNoteLbl?.text = cartData[indexPath.row].additionalNote
cell.quantityLbl?.text = cartData[indexPath.row].recipeQuantity
cell.totalLbl?.text = cartData[indexPath.row].recipePrice
cell.totalCostLbl?.text = cartData[indexPath.row].totalCost
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else {return}
//getting userId from defaults
let CartId = cartData[indexPath.row].cartId
let cartId = CartId
//creating parameters for the post request
let parameters: Parameters=[
"cartId":Int(cartId)
]
//Constant that holds the URL for web service
let URL_SELECT_FROM_CART = "http://localhost:8888/restaurant/deleteFromCart.php?"
Alamofire.request(URL_SELECT_FROM_CART, method: .post, parameters: parameters).responseJSON {
response in
//printing response
print(response)
}
cartData.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
//Fetching from Cart Method
func cart(){
//getting userId from defaults
let defaultValues = UserDefaults.standard
let userId = defaultValues.string(forKey: "userid")
//creating parameters for the post request
let parameters: Parameters=[
"userId":Int(userId!)!
]
//Constant that holds the URL for web service
let URL_SELECT_FROM_CART = "http://localhost:8888/restaurant/cart.php?"
Alamofire.request(URL_SELECT_FROM_CART, method: .post, parameters: parameters).responseJSON {
(response) in
let result = response.data
do{
let decoder = JSONDecoder()
let downloadedCart = try decoder.decode(CartResponse.self, from: result!)
self.cartData = downloadedCart.cartItem
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch {
print(error)
}
}.resume()
}
}
You can use :
import UserNotifications
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadCart"), object: nil)
see more in this answer
You have to call cart() this method in viewWillAppear instead of calling viewDidload
override func viewWillAppear(_ animated: Bool) {
self.cart()
}
I'm trying to set the a string depending on which cell in a tableView is clicked. The BlueLineTableViewController is the one which should capture the user's click.
import UIKit
class BlueLineTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bluelinestations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "bluelinecell", for: indexPath)
let station = bluelinestations[indexPath.row]
cell.textLabel?.text = station.name
cell.imageView?.image = UIImage(named: station.image)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = indexPath.row
if row == 0 {
BlueBelmontTableViewController().feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
}
if row == 1 {
BlueBelmontTableViewController().feed="http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40820&outputType=JSON"
}
}
The BlueBelmontTableViewController's feed variable should change/be set to another url depending on which cell is clicked in the BlueLineTableViewController.
import UIKit
class BlueBelmontTableViewController: UITableViewController {
class Destinations {
var destination: String = ""
var time: String = ""
}
var feed = ""
var dataAvailable = false
var records = [Destinations]()
override func viewDidLoad() {
super.viewDidLoad()
parseData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
for r in records {
r.time = ""
r.destination = ""
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataAvailable ? records.count : 15
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (dataAvailable) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let destinationRow = records[indexPath.row]
cell.textLabel?.text = destinationRow.destination
cell.detailTextLabel?.text = destinationRow.time
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "PlaceholderCell", for: indexPath)
return cell
}
}
func parseData() {
guard let feedURL = URL(string: feed) else {
return
}
let request = URLRequest(url: feedURL)
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
if error != nil
{
print("Error")
}
else {
if let content = data {
do {
let json = try JSONSerialization.jsonObject(with: content, options: []) as? [String:Any] ?? [:]
print(json)
if let ctattimetable = json["ctatt"] as? [String:Any] {
if let estArrivalTime = ctattimetable["eta"] as? [[String:Any]] {
for item in estArrivalTime{
if let headingTowards = item["destNm"] as? String,
let arrivalTime = item["arrT"] as? String {
let record = Destinations()
record.destination = headingTowards
record.time = arrivalTime
self.records.append(record)
}
self.dataAvailable = true
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
catch {
}
}
}
}
task.resume()
}
}
I've tried setting the url in the didSelectRowAt method depending on the indexPath.row as can be seen in BlueLineTableViewController, but it does not seem to do anything. Does anybody know how I would go about doing this?
Below is the Main.storyboard of this part of my project:
Your are not able to pass value because you are setting feed property to the completely new instance of BlueBelmontTableViewController not the one that is added in navigation stack using your segue that you have created from your UITableViewCell to BlueBelmontTableViewController.
What you need to do is override prepareForSegue in your BlueLineTableViewController to pass your value to BlueBelmontTableViewController.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! BlueBelmontTableViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
if indexPath.row == 0 {
vc.feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
}
if indexPath.row == 1 {
vc.feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40820&outputType=JSON"
}
}
}
instead of
BlueBelmontTableViewController().feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
use
self.feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
beacause BlueBelmontTableViewController() is initialing new instance of BlueBelmontTableViewController and you want to change the instance you already have so you should use self instead of creating new instance.