Swift: How to pass data from selected cell using Firebase? - ios

I want to pass data from selected cell to ViewController.
With my code just pass data from the last cell no matter which cell is selected.
' func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return guestsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestTableViewCell
let guest: GuestModel
guest = guestsList[indexPath.row]
cell.guestNameLabel.text = guest.guestName
cell.attendingLabel.text = guest.attendingStatus
cell.menuLabel.text = guest.menuStatus
cell.ageLabel.text = guest.ageStatus
cell.tableLabel.text = guest.tableNo
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toGuestDetails", sender: self
)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toGuestDetails"{
if let indexPath = guestsTableView.indexPathForSelectedRow {
let destinationVC = segue.destination as! GuestDetailsViewController
destinationVC.guestDetail = [guestsList[indexPath.row]]
}
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let guest = guestsList[indexPath.row]
self.guestsList.remove(at: indexPath.row)
self.guestsTableView.reloadData()
self.deleteGuest(id: guest.id!)
}
}
func deleteGuest(id: String){
refGuests.child(id).setValue(nil)
self.guestsTableView.reloadData()
}'
And here is my ViewController with details:
' #IBOutlet var nameLabel: UILabel!
#IBOutlet var emailLabel: UILabel!
#IBOutlet var phoneNoLabel: UILabel!
var ref: DatabaseReference!
let uid = Auth.auth().currentUser?.uid
var guestDetail = [GuestModel]()
override func viewDidLoad() {
super.viewDidLoad()
showGuestDetails()
}
func showGuestDetails(){
ref = Database.database().reference().child("userInfo").child(uid!).child("guests")
ref.queryOrderedByKey().observe(.value) { (snapshot) in
if snapshot.childrenCount>0{
self.guestDetail.removeAll()
for guests in snapshot.children.allObjects as![DataSnapshot]{
let guestObject = guests.value as? [String: AnyObject]
let guestName = guestObject?["guestName"]
let guestFamilyName = guestObject?["guestFamilyName"]
let phone = guestObject?["guestPhoneNumber"]
let email = guestObject?["guestEmail"]
let guestDetails = GuestModel(guestName: guestName as? String, guestFamilyName: (guestFamilyName as? String)!, guestPhoneNumber: phone as? String, guestEmail: email as? String)
let fullName = guestDetails.guestName! + " " + guestDetails.guestFamilyName!
self.nameLabel.text = fullName
self.emailLabel.text = guestDetails.guestEmail
self.phoneNoLabel.text = guestDetails.guestPhoneNumber
self.guestDetail.append(guestDetails)
}
}
}
}

Related

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)
}

TableViewCell data transfer but data late arrived in iOS

I am implementing a function that sends the title of the cell to the JSON file name of the next controller when clicking on a data table cell.
The data passes well, but the data arrives one by one late. If you click the first cell, the data is not gone, and if you click the second cell, the contents of the first cell are transferred.
Where do I adjust data going late one by one? Any ideas?
vc1
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = jsonName
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let country: Countries = countries[indexPath.row]
jsonName = country.asset_name
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath)
let country: Countries = countries[indexPath.row]
cell.imageView?.image = UIImage(named: "flag_" + country.asset_name)
cell.textLabel?.text = country.korean_name
return cell
}
// Data Transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
nextViewController.title = cell.textLabel?.text
nextViewController.secondAssetName = jsonName
}
}
vc2
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var weathers = [Weather]()
var secondAssetName: String?
#IBOutlet weak var tableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let jsonDecoder = JSONDecoder()
guard let dataAsset = NSDataAsset(name: secondAssetName ?? "") else {
return
}
do {
weathers = try jsonDecoder.decode([Weather].self, from: dataAsset.data)
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return weathers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
let weather: Weather = weathers[indexPath.row]
switch weather.state {
case 10:
cell.cellImageView?.image = UIImage(named: "sunny.png")
case 11:
cell.cellImageView?.image = UIImage(named: "cloudy.png")
case 12:
cell.cellImageView?.image = UIImage(named: "rainy.png")
case 13:
cell.cellImageView?.image = UIImage(named: "snowy.png")
default:
return cell
}
cell.cityNameLabel.text = weather.city_name
cell.temperatureLabel.text = String(weather.celsius)
cell.rainfallProbabilityLabel.text = String(weather.rainfall_probability)
return cell
}
}
Add breakpoints to your code. You should see where the problem is. prepare(for: sender:) is being called before tableView(_: didSelectRowAt:), so the first time you tap a cell, jsonName is nil during prepare, then it gets set during didSelect. The second time you tap it, jsonName has the value from the first tap, then it gets updated after.
Put all of your logic in one place. Remove the didSelect method, and update prepare like so:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let nextViewController: SecondViewController = segue.destination as? SecondViewController else {
return
}
guard let cell: UITableViewCell = sender as? UITableViewCell else {
return
}
guard let indexPath = tableView.indexPath(for: cell) else {
return
}
let country: Countries = countries[indexPath.row]
nextViewController.title = country.korean_name
nextViewController.secondAssetName = country.asset_name
}

Pass Data (Label) from TableViewCell to another ViewController

I want to pass the Label from a TableViewCell to a ViewController when I click on the Cell. In the end it should be like twitter, that if you click on a cell with a Label you get passed on a detailViewController with the same Label init.
My Code doesn't work as I just get the blanket Label from the Storyboard...
import UIKit
import Firebase
class JobTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var valueToPass:String!
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
// Arvice return to count jobs
return jobs.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
let valueToPass = currentCell.textLabel?.text
print("value: \(valueToPass)")
performSegue(withIdentifier: "toDetails", sender: valueToPass)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "JobCell", for: indexPath) as! JobTableViewCell
let job = jobs[indexPath.row]
cell.job = job
//spacing
cell.contentView.backgroundColor = UIColor.clear
let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 120))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0.36, 0.39, 0.40, 1.0])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 2.0
whiteRoundedView.layer.shadowOffset = CGSize(width: 0, height: 0)
whiteRoundedView.layer.shadowOpacity = 0.0
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
cell.emojiLabel.text = cell.emojiString
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetails" {
let destinationViewController = segue.destination as! JobDetailViewController
destinationViewController.valueToPass = (sender as? String)!
}
}
My Cell:
import UIKit
import Firebase
class JobTableViewCell: UITableViewCell {
#IBOutlet weak var jobLabel: UILabel!
var job: Job! {
didSet {
jobLabel.text = job.text
}
}
}
Job.Swift:
import Foundation
import Firebase
class Job{
var text: String = ""
let ref: DatabaseReference!
init(text: String) {
self.text = text
ref = Database.database().reference().child("jobs").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["text"] as! String
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"text" : text,
]
}
}
And in my DestinationController:
import UIKit
import Firebase
class JobDetailViewController: UIViewController {
#IBOutlet weak var jobDetail: RoundText!
var valueToPass: String = ""
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
jobDetail.text = valueToPass
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Jobinformation"
}
}
You should not be using cells to store data. You should have a data model that represents the data you are showing in the cells, and you should use the indexPath of the selected cell to look up the data in your data model.
Quick solution:
Change
performSegue(withIdentifier: "yourSegueIdentifer", sender: self) to performSegue(withIdentifier: "yourSegueIdentifer", sender: valueToPass)
2.Your prepare for Segue method should looks like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "yourSegueIdentifer" {
let destinationViewController = segue.destination as! AnotherViewController
destinationViewController.valueToPass = sender as? String
}
}
On AnotherViewController create var valuteToPass: String = "" and set your label.text = valueToPass
But I think you should not use currentCell.textLabel.text value, instead use the original value. (like if you set your currentCell as cell.textLabel.cell = array[indexPath.row], your valueToPass should be valueToPass = array[indexPath.row])
EDIT:
You use didDeselectRowAt method, instead of didSelectRowAt.
Change func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) to
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Don't use global variable, create it in didSelectRowAt.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
let valueToPass = currentCell.textLabel?.text
print("value: \(valuteToPass)")
performSegue(withIdentifier: "toDetails", sender: valueToPass)
}
On DestinationController:
class DestinationController: UIViewController {
var valuteToPass: String = ""
override func viewDidLoad() {
super.viewDidLoad()
jobLabel.text = valueToPass
}
}
EDIT2
JobTableViewController
delete var valueToPass:String!
Change let valueToPass = jobs[indexPath.row].text instead of let valueToPass = currentCell.textLabel?.text
I checked this change in your code, this will work.
Hi I cant comment but im using #Dris answer and I kept getting this error that says
Could not cast value of type 'UITableViewCell' (0x115464e18) to 'NSString' (0x10fa594c8).
The SIGABRT targets the line destinationViewController.valueToPass = (sender as? String)!
Why is that?
this is basically my code
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Determine what to do when a cell in a particular section is selected.
print("did select: \(indexPath.row) ")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel?.text
print("valueToPass: \(String(describing: valueToPass))")
performSegue(withIdentifier: "cellToView", sender: self)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.tableView {
let currentNotif = notificationList[indexPath.row]
cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
cell?.textLabel?.text = currentNotif.notifType
cell?.detailTextLabel?.text = "\(currentNotif.notifTime) \n\(currentNotif.notifContent)"
}
if tableView == self.tableViewAnnounce {
let currentAnnounce = announcementList[indexPath.row]
cell = tableView.dequeueReusableCell(withIdentifier: "cellAnn", for: indexPath) as UITableViewCell
cell?.textLabel?.text = currentAnnounce.annouceType
cell?.detailTextLabel?.text = "\(currentAnnounce.annouceTime) \n\(currentAnnounce.annouceContent)"
}
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cellToView" {
// perform custom segue operation.
let destinationViewController = segue.destination as! ExtendedAnnouncementViewController
destinationViewController.valueToPass = (sender as? String)!
}
}
I'd avoid using a global variable to pass the data to the destination view controller. Defer the lookup until you are ready to pass the data.
And, avoid using force unwrap, it leads to runtime crashes.
Use something like this instead:
let segueIdentifier = "yourSegueIdentifer"
let labelDataSource: [String] = ["SomeText"]
func label(forIndexPath indexPath: IndexPath) -> String? {
let index = indexPath.row
guard labelDataSource.indices.contains(index) else { return nil }
return labelDataSource[index]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: segueIdentifier, sender: indexPath)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard segue.identifier == segueIdentifier,
let indexPath = sender as? IndexPath,
let destinationViewController = segue.destination as? AnotherViewController else { return }
destinationViewController.valuePassed = label(forIndexPath: indexPath)
}

How to pass data in tableview using swift 3?

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?
}

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