iOS How to send cell data to another VC use parse Swift - ios

How i can send data from my table view cell, to another VC when in tap on cell.
My code for fetch data from DB:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! cellRequestsTVC
let good = data[indexPath.row]
name = good["username"] as! String
cell.userNameLable.text = "#\(name)"
area = good["place"] as! String
cell.areaLable.text = "\(area)"
cell.descriptionLable.text = good["description"] as? String
cell.priorityLable.text = "Priority " + ((good["priority"] as? Int)?.description)!
let imageProblems = good["image"] as? PFFile
imageProblems?.getDataInBackground{ (imageData, error)in
if imageData != nil {
let image = UIImage(data: imageData!)
cell.problemImage.image = image
}
}
return cell
}
It's working perfect. But now my target open data from cell in another VC.
Example:
Example

You have to implement UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let good = data[indexPath.row]
// Here you can either perform a segue or push view controller to UINavigationController
//Push View controller
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : DetailViewController = storyBoard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.sharedData = data // here you pass data
self.navigationController?.pushViewController(vc, animated: true)
}
In DetailViewController create object of data with required type
var sharedData : [String : Any]! // Take optional variable if object can be nil & here assuming data contains object of type [String : Any]
You can look the documentation here
UITableViewDelegate

Related

When select cell to pass data always shows nil in the next ViewController using Swift

I am trying to pass data when select or press cell in TableView, it's working and I can print the result while select that cell.
The problem when the second view shows the data is nil.
her is the code when when select cell:
var feedItems: NSArray = NSArray()
var selectedPlayer : UsersModel = UsersModel()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of feed items
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve cell
let cellIdentifier: String = "BasicCell"
let myCell: WinnerTableCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! WinnerTableCell
// Get the location to be shown
let item: UsersModel = feedItems[indexPath.row] as! UsersModel
// Get references to labels of cell
myCell.lbTextName!.text = item.name
myCell.lbScore!.text = item.score
let imageURL = URL(string: "https://mywebsite.com/image-upload/img/\(item.userImage ?? "nil")")
myCell.userImage.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "nullImageQuestion.png"))
return myCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = feedItems[indexPath.row] as! UsersModel
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.name = selectedPlayer.name ?? "nil"
print("Print When select cell \(selectedPlayer.name ?? "nil")")
}
And her is the code in the second view:
#IBOutlet weak var lbName: UILabel!
#IBOutlet weak var userImage: UIImageView!
var name = ""
var selectedUser : UsersModel?
override func viewDidLoad() {
super.viewDidLoad()
lbName.text = selectedUser?.name
print("Print when second view open via viewdidload \(selectedUser?.name ?? "nil")")
// Do any additional setup after loading the view.
}
I tried to print from the second view but it shows nothing. What mistake I did?
This is what i have out when print:
There is something I can not understand when I print, it start with the secondview?
Note: I am not using Navigation Controller.
Thanks
There are two serious issues:
The main issue is that you assign the name to the name property but you are assigning selectedUser?.name to the label in the destination controller which is of course nil
The second issue has already been fixed by Taimoor: You have to present or push the controller.
So replace didSelect with
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = feedItems[indexPath.row] as! UsersModel
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.selectedUser = selectedPlayer
self.present(nextViewController, animated: true)
}
And please never use NSArray in Swift. Declare the data source array
var feedItems = [UsersModel]() // why not just `User`?
and delete all unnecessary type casts.
You have to use pushViewController to take the data to next screen. Just add one more line in didSelectRowAt function as below:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = feedItems[indexPath.row] as! UsersModel
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.name = selectedPlayer.name ?? "nil"
print("Selcted \(selectedPlayer.name ?? "nil")")
self.navigationController?.pushViewController(nextViewController, animated: true)
}
This will take your data to next screen.
You can also try to execute "nextViewController.loadViewIfNeeded()"
Because you just created this ViewController, but did not present it, according to your hierarchical relationship, choose to use prensent or push to present it, it will execute "ViewDidload()"
you've given feedItems's array type NSArray() instead to
var feedItems: UsersModel = [ ]
or you assign name to selectedUser?.name of next page so that assign nil value
or that probably wrong
you have to implement at didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PlayersDetails") as! PlayersDetails
nextViewController.name = feedItems[indexPath.row].name as! UsersModel
print("Selcted \(selectedPlayer.name ?? "nil")")
self.navigationController?.pushViewController(nextViewController, animated: true)
}

Passing selected Image in cell image

My application consists of 2 tap bars.
First tap is TableView and second - VC.
When I'm on first VC, I selected picture and press the button, which should transfer the selected picture on cell image.
I'm trying to save image in UserDefaults but then it turns out that all lines are with the same picture
In my VC, I save TextField by this method:
func saveButton() {
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items:[String]
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(nameTextField.text!)
} else {
items = [nameTextField.text!]
}
UserDefaults.standard.set(items, forKey: "items")
nameTextField.text = ""
navigationController?.popViewController(animated: true)
}
And choose the image
Then I tap "Save" button
In my Table view:
override func viewDidAppear(_ animated: Bool) {
// Load Item Func
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
}
table.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellPrototype
// Configure the cell...
cell.pointNameLabel.text = items[indexPath.row]
return cell
}
You can pass image by creating a variable in Second VC like this
UITableView Delegate Method
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as? YourCell
if let DetailVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController{
DetailVC.Selected_image = cell.YourImageView.image
self.navigationController?.pushViewController(DetailVC,animated: true)
}
}
Create Variable in Second VC
class DetailViewController: UIViewController {
var Selected_image: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
print(Selected_image)
}
}
You can pass the image from cell to detailViewController here is partail pseudo Code
tableView (cell , didSelectCellAtIndexPath) {
if let cell = cell as? CustomCell {
let image = cell.image
let detailVC = DetailViewController(..) // instantiate from storyboard
detailVC.selectedImage = image
navigationViewController.push(detailVC)
}
}
Class DetailVC: UIViewController {
var selectedImage: UIImage!
// can access image anywhere in this class after passing
}

Parsing multiple images in swift from JSON

Json has multiple images,
img1
Json has date with multiple images, I want show Date and first image of that Date in tableview, working fine.
img2
Note :
when click any cell in tableview, display that Date with all images in collection view, But am parsing only first image of that Date,that image only showing in collection view
how to parse all images from Json and pass to collection view from tableview, and display images into collocation view
img3
this is the code ...
json Code
if errorCode == "0" {
if let Media_list = jsonData["events"] as? [Any] {
self.Mediainfo.removeAll()
for i in 0 ..< Media_list.count {
if let MediaEventData = Media_list[i] as? [String: Any] {
var eventImages = MediaEventData["eventImages"] as? [[String: Any]]
if (eventImages?.count)! > 0 {
let bannerImage = eventImages?[0]["bannerImage"] as? String
print(bannerImage as Any)
self.imageUrl = self.url+"/images/events/" + String(describing: bannerImage!)
self.Mediainfo.append(MediaEvent(
eventId: MediaEventData["eventId"]as?String,
date: MediaEventData["date"]as?String,
eventname: MediaEventData["eventName"]as?String,
bannerImages: self.imageUrl
)
)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Media", for: indexPath)as! MediaCustomTableViewCell
let row = indexPath.row
let media = Mediainfo[row] as MediaEvent
cell.DisplayDate.text = media.date
cell.DisplayName.text = media.eventName
cell.selectionStyle = .none
cell.DisplayImage.downloadImageFrom(link:media.bannerImages, contentMode: UIViewContentMode.scaleAspectFit)
return cell
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let media = Mediainfo[(indexPath.row)] as MediaEvent
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "IMAGEVID") as! UITabBarController
if let viewControllers = tabBarController.viewControllers,
let imageController = viewControllers.first as? ImagesCollectionViewController {
imageController.RecivedData1 = media.bannerImages
}
navigationController?.pushViewController(tabBarController, animated: true)
}
collection view Code :
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
cell.ImageviewCell.downloadImageFrom(link:nameofImages[indexPath.row], contentMode: UIViewContentMode.scaleAspectFit)
return cell
}
pls help me......!
u can do soemthing like this
let eventImages = MediaEventData["eventImages"] as? [[String: Any]]
if (eventImages?.count)! > 0 {
for i in 0...eventImages.count{
let bannerImage = eventImages?[i]["bannerImage"] as? String
self.imageUrl = self.url+"/images/events/" + String(describing: bannerImage!)
self.Mediainfo.append(bannerImage)
// or like u did u can append to array
self.Mediainfo.append(MediaEvent(
eventId: MediaEventData["eventId"]as?String,
date: MediaEventData["date"]as?String,
eventname: MediaEventData["eventName"]as?String,
bannerImages: self.imageUrl
)
} }
In didselect
let media = Mediainfo[(indexPath.row)] as MediaEvent
imageController.RecivedData1 = media.bannerImages
Your doing like this Means Your are slecting a particular cell and
that index your are passing to NextVC.
if you want to show all images You should pass complete array to
nextvc
You should declare a array of same type Mediainfo array in Next VC
and do like
EX: imageController.array = Mediainfo

working with cell on tableview using swift 2

I am developing a app using Swift 2. In my app I am parsing JSON data to a table view. When I tap a cell it successfully moves to another view controller but I am unable to fetch the json data.
This is the code in my view controller:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath){
var cell = self.TableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! CustomTableCell
let strbookdetail : NSString=arrDict[indexPath.row] .valueForKey("booking_detail") as! NSString
let strdrop : NSString=arrDict[indexPath.row] .valueForKey("drop_address") as! NSString
cell.Bookdetail.text=strbookdetail as String
cell.Dropaddress.text=strdrop as String
return cell as CustomTableCell
}
//It helps to parse JSON data to table view.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
TableView.deselectRowAtIndexPath(indexPath, animated: true)
let tripcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("UpcomingController") as! Secondcontroller
navigationController?.pushViewController(tripcontroller, animated: true)
}
When tapping on the cell it helps to move to other view controller SecondController
In my SecondController I have two UILabels. In those labels I want to show data i.e strbookdetail and strdrop
How can I pass a reference between the two view controllers?
It is easy to do using property pass data:
In 2th vc:
var dataFromBeforeVC:[String:String] = [String:String]()
override func viewDidLoad() {
super.viewDidLoad()
initData ()
}
func initData() {
// set data strbookdetail and strdrop to labelOne & labelTwo
labelOne.text = dataFromBeforeVC["strdrop"]
labelTwo.text = dataFromBeforeVC["strbookdetail"]
}
In 1th vc:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
TableView.deselectRowAtIndexPath(indexPath, animated: true)
let tripcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("UpcomingController") as! Secondcontroller
let cell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
let strbookdetail : NSString=arrDict[indexPath.row] .valueForKey("booking_detail") as! NSString
let strdrop : NSString=arrDict[indexPath.row] .valueForKey("drop_address") as! NSString
tripcontroller.dataFromBeforeVC = [
"strdrop":strbookdetail,
"strdrop":strbookdetail
]
self.navigationController?.pushViewController(tripcontroller, animated: true)
}

Swift 2 passing data through segue from UIcollectionview (indexpath.row)

I'm trying to pass data (value of dict["IDD"] ) via segue.
(XCODE 7.2)
Here my code:
var arrRes = [[String:AnyObject]]()
var dict = [:]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! collectionViewCell
var dict = arrRes[indexPath.row]
let newPrice = dict["price"]!.stringByReplacingOccurrencesOfString(".", withString: ",")
cell.lblPrice.text = "€\(newPrice)"
cell.lblTitle.text = dict["title"] as? String
cell.lblBrand.text = dict["brand"] as? String
cell.lblIDD.text = dict["IDD"] as? String
cell.imageView!.image = UIImage(named: "loading.gif") //set placeholder image first.
dispatch_async(dispatch_get_main_queue()) {
cell.imageView!.downloadImageFrom(link: dict["image"] as! String, contentMode: UIViewContentMode.ScaleAspectFit) //set your image from link array.
}
return cell
}
But I don't kwon how to setup the performseguewithidentifier for segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "homeDetailSegue")
{
let cell = sender as! UICollectionViewCell
let detailView = segue.destinationViewController as! dettaglio
let dict = arrRes[(self.myCollectionView.indexPathForCell(cell))!]
detailView.setnomeOggetto(arrRes["IDD"] as! String)
}
}
I have no problem with tableviews but this is my first time with collectionView
Could please someone help me?
Kind Regards
Thank You very Much
Fabio
I tried the solution for your question and now I got it.Try below the solution.
Before that go to stroyborad click the destinationViewController(here detailViewController)
Then click Identity Inspector of the Right Navigation bar.
Once you click the you can see the Identity under Custom Class
No click Identity then give 'detailsVC' or whatever you want in Storyboard ID.
Now in CollectionViewDelegate Method
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
// handle tap events
print("You selected cell #\(indexPath.item)!")
let detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("detailVC") as! DetailViewController
detailVC.passDataToLabel = String (indexPath.item )
print(detailVC.passDataToLabel)
self.navigationController?.pushViewController(detailVC, animated: true)
}

Resources