How to pass data in tableview using swift 3? - ios

I want to get, store & pass an URL in tableview to another table view in swift 3?
I am trying a lot but i can't do it? Please help me.
class EpisodesTableViewController: UITableViewController
{
var episodes = Episode
var audioPlayer : AVAudioPlayer!
var selectedVideoIndex: Int!
override func viewDidLoad()
{
super.viewDidLoad()
episodes = Episode.downloadAllEpisodes()
self.tableView.reloadData()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return episodes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Episode Cell", for: indexPath) as! EpisodeTableViewCell
let episode = episodes[indexPath.row]
cell.episode = episode
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "secondView", sender: indexPath.row)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var next = segue.PViewController as! PlayTableViewController
next.index = sender as? Int
}
here is the another code
class PlayTableViewController: UITableViewController
{
var play = [PlayView]()
var audioPlayer : AVAudioPlayer!
var indexOfCell:Int?
override func viewDidLoad() {
super.viewDidLoad()
super.viewDidLoad()
play = PlayView.downloadAllEpisodes()
self.tableView.reloadData()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return play.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Player Cell", for: indexPath) as! PlayerTableViewCell
let playV = play[indexPath.row]
cell.PV = playV
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
let episode = play[indexPath.row]
let player = AVPlayer(url: episode.url!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
class PlayView {
var name: String?
var thumbnailURL: URL?
var url: URL?
init(name: String, thumbnailURL: URL, url: URL)
{
self.name = name
self.thumbnailURL = thumbnailURL
self.url = url
}
init(pvDictionary: [String : Any]) {
self.name = pvDictionary["name"] as? String
// url, createdAt, author, thumbnailURL
url = URL(string: pvDictionary["alt_url"] as! String)
thumbnailURL = URL(string: pvDictionary["alt_image"] as! String)
}
static func downloadAllEpisodes() -> [PlayView]
{
var playView = [PlayView]()
let url2 = URL(string: "http://nix2.iotabdapps.com/apk/items.json")
let jsonData = try? Data(contentsOf: url2!)
if let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {
let pvDictionaries = jsonDictionary["items"] as! [[String : Any]]
for pvDictionary in pvDictionaries {
let newPlayView = PlayView(pvDictionary: pvDictionary)
playView.append(newPlayView)
}
}
return playView
}
}
I want to get the URL from tableview when user clicked.
I want to get an URL when click the Tableview then save it and pass it to the another tableview.
I can do this in JAVA but i am failed to convert in SWIFT 3
here is my java Example
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
resultp = data.get(position);
Intent intent = new Intent(context, FragmentDemoActivity.class);
intent.putExtra("videoId", resultp.get(Main.VIDEO_ID));
context.startActivity(intent);
// Get the position
}
});
return itemView;
Can anyone help me please?

You need to implement prepareForSegue method
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "secondView", sender: indexPath.row)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var next = segue.destinationViewController as! PlayTableViewController
next.indexOfCell = sender as? Int
}
//
class PlayTableViewController:UITableViewController
{
var indexOfCell:Int?
}

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.
}
*/
}

Pass API data when tap on CollectionVC to TableVC

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)&sector=\(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)
}

Ambiguous reference to member 'tableView(_:numberOfRowsInSection:)'

Wanna pass data from a ViewController which has TableView init, to another ViewController. But it's showing me the error "Ambiguous reference to member 'tableView(_:numberOfRowsInSection:)' "
#IBOutlet weak var completedCaseTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
completedCaseTableView.delegate = self
completedCaseTableView.dataSource = self
// Do any additional setup after loading the view.
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usrNameList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CompletedCaseCell", for: indexPath) as! Admin_CompletedCases_TableViewCell
cell.completedTktNum.text = usrTktList[indexPath.row]
cell.completedUsrName.text = usrNameList[indexPath.row]
cell.completedCustomerDp.image = UIImage(named: imageList[indexPath.row])
cell.completedPostedDate.text = datesList[indexPath.row]
cell.completedUsrReason.text = reasonList[indexPath.row]
cell.statusOfCase.text = statusList[indexPath.row]
return cell
}
public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "AdminCompletedDetailsSegue" ){
let adminCompletedDvc = segue.destination as! Admin_Completed_Details_ViewController
if let indexPath = self.tableView.indexPathForSelectedRow {
adminCompletedDvc.newTktNumNew = usrTktList[indexPath.row] as String
adminCompletedDvc.customerUsernameAdmnNew = usrNameList[indexPath.row] as String
adminCompletedDvc.postedDateAdmnNew = datesList[indexPath.row] as String
adminCompletedDvc.customerReasonAdmnNew = reasonList[indexPath.row] as String
adminCompletedDvc.customerCommentsAdmnNew = commentList[indexPath.row] as String
adminCompletedDvc.customerImgAdmnNew = imageList[indexPath.row] as String
}
}
}
The problem is that there is nothing in your view controller called self.tableView. Its name is completedCaseTableView. So change this:
if let indexPath = self.tableView.indexPathForSelectedRow {
to this:
if let indexPath = self.completedCaseTableView.indexPathForSelectedRow {

Swift 3 - Setting variable in TableViewController swift file depending on cell clicked

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.

UitableView selected cell to the other view

I have a UITableView where data is loaded from a database, a JSON. How do I get this when I select a line, which is taken in another view?
The automarke is to be selected in the tableview and displayed in the label of the other view.
class AutoMarkeTableView: UITableViewController {
var items = [[String:AnyObject]]()
#IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "URL_LINK")!
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: url) { (data, response, error) in
// JSON parsen und Ergebnis in eine Liste von assoziativen Arrays wandeln
let jsonData = try! JSONSerialization.jsonObject(with: data!, options: [])
self.items = jsonData as! [[String:AnyObject]]
// UI-Darstellung aktualisieren
OperationQueue.main.addOperation {
self.tableView.reloadData()
}
}
task.resume()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "markeCell", for: indexPath)
let item = items[indexPath.row]
cell.textLabel?.text = item["makename"] as? String
return cell
}
}
class FahrzeugAngabenView: UIViewController {
#IBOutlet weak var itemMarkeLabel: UILabel!
}
You could temporarily save the selected item in a variable. Something like this:
var selectedItem: Item?
func tableView(tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedItem = items[indexPath.row]
self.performSegue(withIdentifier: "auto", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "auto" {
let destVc = segue.destination as! FahrzeugAngabenView
destVc.selectedItemName = selectedItem.title
selectedItem = nil
}
}
Not the most elegant solution, but i would expect this to work.

Resources