I have little bit problem with my search bar. As you see on screens. When I dont filter anything and i click on first, it shows me first detail screen, when I click on second, it shows me second screen with detail, but when I filter something for example second (like in last screen) and click on result, it shows me first screen, which is wrong, I want to see second screen with detail. My code is here:
import UIKit
//array definiton
var names = [String]()
var namesDesc = [String]()
var namesDescWhereTo = [String]()
var imageArr = [UIImage(named: "Alobal")!,UIImage(named: "Akumulátory")!,UIImage(named: "Akvária")!,UIImage(named: "Autovrak")!,UIImage(named: "Autosklo")!]
var myIndex = 0
class mainTableViewController: UITableViewController, UISearchResultsUpdating {
//definition variables for VC
var namesTableView = names
var filteredNames = [String]()
var searchController : UISearchController!
var resultsController = UITableViewController()
override func viewDidLoad() {
super.viewDidLoad()
//load file with names - names.txt
do {
//definice názvu souboru + oddělovače
if let path = Bundle.main.path(forResource: "names", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
names = data.components(separatedBy: "\n")
}
} catch let err as NSError {
//pokud je nějaký error
print(err)
}
//load file with descriptions - namesDesc.txt
do {
//definice názvu souboru + oddělovače
if let path = Bundle.main.path(forResource: "namesDesc", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
namesDesc = data.components(separatedBy: "\n")
}
} catch let err as NSError {
//pokud je nějaký error
print(err)
}
//load file with information "where to" - namesDescWhereTo.txt
do {
//definice názvu souboru + oddělovače
if let path = Bundle.main.path(forResource: "namesDescWhereTo", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
namesDescWhereTo = data.components(separatedBy: "\n")
}
} catch let err as NSError {
//pokud je nějaký error
print(err)
}
namesTableView = names
//definiton main title + call method setupNavBar()
self.title = "Where to?"
setupNavBar()
self.resultsController.tableView.dataSource = self
self.resultsController.tableView.delegate = self
self.searchController = UISearchController(searchResultsController: self.resultsController)
self.tableView.tableHeaderView = self.searchController.searchBar
self.searchController.searchResultsUpdater = self
self.searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
}
//method where I define large titles
func setupNavBar() {
navigationController?.navigationBar.prefersLargeTitles = true
}
func updateSearchResults(for searchController: UISearchController) {
self.filteredNames = self.namesTableView.filter { (name:String) -> Bool in
if name.lowercased().contains(self.searchController.searchBar.text!.lowercased()) {
return true
} else {
return false
}
}
//reloading
self.resultsController.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return self.namesTableView.count
} else {
return self.filteredNames.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if tableView == self.tableView {
cell.textLabel?.text = self.namesTableView[indexPath.row]
} else {
cell.textLabel?.text = self.filteredNames[indexPath.row]
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
performSegue(withIdentifier: "segue", sender: self)
}
}
Thanks for help.
In all your other datasource methods (cellForRow, numberOfRows etc), you did this:
if tableView == self.tableView {
// use the normal data source array
} else {
// use the filtered data source array
}
So why not do this in prepareForSegue, where you pass the item corresponding to myIndex to the next controller?
You don't have an instance of the tableView so you can't check whether the user is searching, can you?
Other than checking whether the passed in table view is the original table view, you can check the isActive property of searchController:
if searchController.isActive && searchController.searchBar.text != "" {
// use the filtered data
} else {
// use the normal data
}
#Sweeper I added prepareForSegue, but problem is same :( in the destination VC after filtering i cant see right results. This i add to main VC.
override func prepare(
for segue: UIStoryboardSegue, sender: Any ? ) {
if segue.identifier == "segue" {
if let indexPath = tableView.indexPathForSelectedRow {
let resultName: String
if isFiltering() {
resultName = filteredNames[indexPath.row]
} else {
resultName = namesTableView[indexPath.row]
}
let controller = segue.destination as!ViewController
controller.test = resultName
}
}}
And this I have in destination VC in viewDidLoad():
title = test
recLabelDesc.text = test
Related
I followed this tutorial
https://www.youtube.com/watch?v=35mKM4IkHS8&lc=UgztyK4XjUuAOrKk0XJ4AaABAg.9LtwRc_M0Gv9Nt8GIlAzDo
Basically I made a NotePad App that has a core data save function.
I made this app on another view controller
So There is MainViewController > NoteViewViewController
The first time I click the notepad section it loads core data perfectly well, but if I close out the NoteView and reopen it -- it duplicates all the saved Notes in Core Data
Here is the. Note ViewController
import UIKit
import CoreData
var noteList = [Note]()
class NoteTableView: UITableViewController
{
func nonDeletedNotes() -> [Note]
{
var noDeleteNoteList = [Note]()
for note in noteList
{
if(note.deletedDate == nil)
{
noDeleteNoteList.append(note)
}
}
return noDeleteNoteList
}
var firstLoad = true
override func viewDidLoad() {
if(firstLoad == true)
{
firstLoad = false
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
do {
let results:NSArray = try context.fetch(request) as NSArray
for result in results
{
let note = result as! Note
noteList.append(note)
}
}
catch
{
print("Fetch Failed")
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell
{
let noteCell = tableView.dequeueReusableCell(withIdentifier: "noteCellID", for: indexPath) as! NoteCell
let thisNote: Note!
thisNote = nonDeletedNotes()[indexPath.row]
noteCell.titleLabel.text = thisNote.title
noteCell.descLabel.text = thisNote.desc1
return noteCell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return nonDeletedNotes().count
}
override func viewDidAppear(_ animated: Bool) {
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
self.performSegue(withIdentifier: "editNote", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if(segue.identifier == "editNote")
{
let indexPath = tableView.indexPathForSelectedRow!
let noteDetail = segue.destination as? FocusWheelViewController
let selectedNote : Note!
selectedNote = nonDeletedNotes()[indexPath.row]
noteDetail!.selectedNote = selectedNote
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
I'm sure there is a common solution but I'm not sure what it is and wasn't able to follow the posts asking similar questions as my code was different and I truthfully don't understand the mechanics well enough to apply other answers to this
I found the easiest solution was to just add these two lines so the table view refreshed every-time, then loaded the data
noteList.removeAll()
tableView.reloadData()
So the code looks something like this:
var firstLoad = true
override func viewDidLoad() {
if(firstLoad == true)
{
noteList.removeAll() //NEWCODE
tableView.reloadData() //NEWCODE
firstLoad = false
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
do {
let results:NSArray = try context.fetch(request) as NSArray
for result in results
{
let note = result as! Note
noteList.append(note)
}
}
catch
{
print("Fetch Failed")
}
}
}
The problem is var firstLoad = true. Because every time the controller start, firtLoad always true and the app will get data from Coredata and append to noteList.
The solution is UserDefaults. The first time when you run app, firstLoad always true. So you need to save the value bool of firstLoad to UserDefaults
// Set
UserDefaults.standard.setValue(true, forKey: "firstLoad")
// Get
UserDefaults.standard.bool(forKey: "firstLoad")
import UIKit
import CoreData
class NoteTableView: UITableViewController{
var noteList = [Note]()
func nonDeletedNotes() -> [Note]{
var noDeleteNoteList = [Note]()
for note in noteList {
if(note.deletedDate == nil) {
noDeleteNoteList.append(note)
}
}
return noDeleteNoteList
}
override func viewDidLoad() {
if noteList.count == 0 {
if(UserDefaults.standard.bool(forKey: "firstLoad") == true){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
do {
let results:NSArray = try context.fetch(request) as NSArray
for result in results
{
let note = result as! Note
noteList.append(note)
UserDefaults.standard.setValue(false, forKey: "firstLoad")
}
}
catch {
print("Fetch Failed")
}
}
} {
else {
UserDefaults.standard.setValue(false, forKey: "firstLoad")
}
}
}
}
And maybe you need to check duplicate value when get data from CoreData.
I got a plist object which contains all the words key=english and value=malay and I assigned in to 2 different arrays which is english and malay. Now I want a textfield where I want to search the english word and print the malay word in the label.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var selectedLabel: UILabel!
#IBOutlet weak var searchText: UITextField!
#IBOutlet weak var wordTable: UITableView!
var english = [String]()
var malay = [String]()
var words: [String: String] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
wordTable.dataSource = self
wordTable.delegate = self
searchText.delegate = self
if let path = Bundle.main.path(forResource: "words", ofType: "plist"){
if let plistData = FileManager.default.contents(atPath: path){
do {
let plistObject = try PropertyListSerialization.propertyList(from: plistData, options: PropertyListSerialization.ReadOptions(), format: nil)
words = (plistObject as? [String: String])!
english = [String] (words.keys)
malay = [String] (words.values)
} catch {
print("Error Serialize")
}
} else {
print("Error reading data")
}
} else {
print("Property list")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return english.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
cell = tableView.dequeueReusableCell(withIdentifier: "tabelCell")
if cell == nil {
cell = UITableViewCell(
style: UITableViewCellStyle.value2,
reuseIdentifier: "tableCell")
print("creating a table cell")
}
cell!.textLabel!.text = english[indexPath.row]
cell!.detailTextLabel?.text = malay[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedLabel.text = malay[indexPath.row]
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
#IBAction func searchBtn(_ sender: UIButton) {
let result = words.filter {$0.key == searchText.text}
if result.count > 0 {
print(result)
selectedLabel.text! = result.values //error
} else {
print("Not found")
}
}
}
the output I expecting is textfield(Bus) which is english word then in the label show me the malay word(Bas)
You have a plist file as a Dictionary. So you can get the dictionary object from the plist file and already answer here.
Make a structure for better data binding.
struct Word {
var english: String
var malay: String
}
Then declare an array of words globally in your ViewController.
var words: [Word] = [] // An empty array
In viewDidLoad: fetch data from plist file.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
wordTable.dataSource = self
wordTable.delegate = self
searchText.delegate = self
if let path = Bundle.main.path(forResource: "words", ofType: "plist") {
if let plistData = FileManager.default.contents(atPath: path){
do {
guard let plistObject = try PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [String: String] else {
// Plist is not [String: String]
return
}
// Here you need to change the code. Converting the dictionary into struct array
var words: [Word] = plistObject.map {Word(english: $0.key, malay: $0.value)}
/// Then sort by english word if needed
words.sorted {$0.english < $1.english}
} catch {
print("Error Serialize")
}
} else {
print("Error reading data")
}
} else {
print("Property list")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
Update your cell data as well.
cell!.textLabel!.text = words[indexPath.row].english
cell!.detailTextLabel?.text = words[indexPath.row].malay
And your button action with minor modification:
#IBAction func searchBtn(_ sender: UIButton) {
let result = words.filter {$0.english == searchedText}
if let word = result.first {
selectedLabel.text = word.malay
} else {
selectedLabel.text = "" // No data found
}
}
You can replace $0.english == searchedText with {$0.english.contains(searchedText)} if you want to filter with contains, But in that case you might get the multiple result. I assume that in your case you need it as a translator so use ==.
Why don't you search in your plist object? I think it is simpler
#IBAction func searchBtn(_ sender: UIButton) {
guard let words = plistObject as? [String: String], let key = searchText.text else { return }
selectedLabel.text = words[key] ?? ""
}
Something like this.
The app crashes with the following error when the search bar is tapped:
Not able to understand why?
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier ContactCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
This is my code:
import UIKit
class ContactViewController: UITableViewController, UISearchResultsUpdating {
var dataSource: [Contact] = []
var filteredResult = [Contact]()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
downloadJSONUrl()
}
func downloadJSONUrl() {
let urlString = "https://us-central1-practo-contacts-sample.cloudfunctions.net/get"
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response , error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
if let NameArray = jsonObj?.value(forKey: "contacts") as? [[String: Any]] {
for names in NameArray {
var cont = Contact()
if let name = names["name"] as? String {
cont.name = name
}
if let ph = names["number"] as? String {
cont.phoneNumber = ph
}
self.dataSource.append(cont)
}
self.dataSource.sort {$0.name.lowercased() < $1.name.lowercased()}
}
OperationQueue.main.addOperation {
self.tableView.reloadData()
}
}
}).resume()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as UITableViewCell
let contact = self.dataSource[indexPath.row]
cell.textLabel?.text = contact.name
cell.detailTextLabel?.text = contact.phoneNumber
return cell
}
func updateSearchResults(for searchController: UISearchController) {
if searchController.searchBar.text! == "" {
filteredResult = dataSource
} else {
filteredResult = dataSource.filter { $0.name.lowercased().contains(searchController.searchBar.text!.lowercased()) }
}
self.tableView.reloadData()
}
#IBAction func unwindToContactList(segue: UIStoryboardSegue) {
guard let viewController = segue.source as? AddOrEditViewController else { return }
if let name = viewController.nameTextField.text, let phoneNumber = viewController.phoneNumberTextField.text {
let contact = Contact(name: name, phoneNumber: phoneNumber)
self.dataSource.append(contact)
tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "contactDetailsSegue" {
guard let viewController = segue.destination as? ContactDetialsViewController else {
return
}
guard let indexPath = tableView.indexPathForSelectedRow else { return }
let contact = self.dataSource[indexPath.row]
viewController.contact = contact
}
}
}
Are you sure that you have set the identifier for the cell on the storyboard and the identifier name is the same used on the code "ContactCell"?
I have an app that I would like to target to iOS 7, but am currently unable to do so because it contains a UISearchController which is only available for iOS 8 and up.
I've been trying to modify the search bar with a UISearchDisplayController so that it works in iOS 7, but I just can't get it to work and am getting a little frustrated. So as a temporary measure (while I get better at coding), I would like to disable the search bar for any iOS below 8.0 - which won't impact the end user too much because its only one screen in a much larger app.
The problem is that I haven't been able to figure out how to do this conditionally (e.g., with "if #available(iOS 8.0, *)" ) because the variables "searchController" and "controller" are defined outside of a method or function and so can't be assigned conditionally. I guess conditional statements can only be used within functions and methods? (still learning, as you can see).
So can anyone offer a way for me to conditionally disable the search bar here so I can target iOS 7? My code for this class is below. Thanks!
class RegData2: UITableViewController, UISearchResultsUpdating {
let model = Model()
var prevArray = [String]()
var selectionPrev = String()
var filteredTableData = [String]()
var searchController = UISearchController()
let controller = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.searchController = ({
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
self.definesPresentationContext = true
return controller
})()
// Reload the table
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.searchController.active) && (controller.searchBar.text != "") {
return self.filteredTableData.count
}
else {
return prevArray.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
cell.textLabel?.font = UIFont.boldSystemFontOfSize(18)
if (self.searchController.active) && (controller.searchBar.text != "") {
cell.textLabel?.text = filteredTableData[indexPath.row]
return cell
}
else {
cell.textLabel?.text = prevArray[indexPath.row]
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
controller.searchBar.resignFirstResponder()
performSegueWithIdentifier("regData2ToRegView", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "regData2ToRegView" {
let regView = segue.destinationViewController as! RegView
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
var selection : String = prevArray[indexPath.row]
if (self.searchController.active) && (self.controller.searchBar.text != "") {
selection = self.filteredTableData[indexPath.row]
}
else {
selection = self.prevArray[indexPath.row]
}
regView.prevSelection = selection
regView.prevSelectionType = selectionPrev
}
}
func updateSearchResultsForSearchController(searchController: UISearchController)
{
if searchController.searchBar.text != ""{
filteredTableData.removeAll(keepCapacity: true)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchController.searchBar.text!)
if self.selectionPrev != "ed" {
let array = (self.prevArray as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
// edAlert = 0
} else {
let array = (self.prevArray as NSArray).filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
// edAlert = 1
}
self.tableView.reloadData()
} else {
self.tableView.reloadData()
}
}
}
To check version you can do this:
switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
println("iOS >= 8.0")
case .OrderedAscending:
println("iOS < 8.0")
}
But most likely you just need to check if the class is available and then instantiate it:
if NSClassFromString("UISearchController") != nil {
// init and use ...
}
This is called "weakly linked" class.
EDIT:
Also you can use preprocessor to include/exclude any code before compilation, i.e.:
#if __IPHONE_8_0
class RegData2: UITableViewController, UISearchResultsUpdating {
#else
class RegData2: UITableViewController {
#endif
More info here and here and also here.
I'm trying to fill a tableView with some products from my MySQL database (using a PHP POST file) and at the moment everything is fine, but when I select a "Cell", the prepareForSegue is triggered, but the indexPathForSelectedRow is wrong, so it's showing a different product.
Here is my full code, I hope you can tell me something because I don't know why is this happening, I have tried a lot of things and I'm out of options...!
TableViewController.swift
import UIKit
class ListadoBuscarResultadosTableViewController: UITableViewController {
var option: String = ""
var productos = [Producto]()
var refreshControl2:UIRefreshControl!
var imageCache = [String:UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
requestPost()
title = self.option
tableView.allowsMultipleSelection = true
tableView.scrollsToTop = true
self.tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
func refresh(sender:AnyObject) {
requestPost()
self.refreshControl2.endRefreshing()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return productos.count
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// Define the initial state (Before the animation)
cell.alpha = 0.25
// Define the final state (After the animation)
UIView.animateWithDuration(1.0, animations: { cell.alpha = 1 })
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// try to reuse cell
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! BuscarCellTableViewCell
cell.selectionStyle = .None
//cell.nombre.text = productos[indexPath.row].nombre
//cell.marca.text = productos[indexPath.row].marca
//println(cell.nombre.text)
// get the deal image
let currentImage = productos[indexPath.row].imagen
let unwrappedImage = currentImage
var image = self.imageCache[unwrappedImage]
let imageUrl = NSURL(string: productos[indexPath.row].imagen)
// reset reused cell image to placeholder
cell.imagen.image = UIImage(named: "")
// async image
if image == nil {
let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
image = UIImage(data: data)
self.imageCache[unwrappedImage] = image
dispatch_async(dispatch_get_main_queue(), {
cell.imagen.image = image
cell.nombre.text = self.productos[indexPath.row].nombre
cell.marca.text = self.productos[indexPath.row].marca
})
}
else {
cell.nombre.text = self.productos[indexPath.row].nombre
cell.marca.text = self.productos[indexPath.row].marca
}
})
}
else {
cell.imagen.image = image
cell.nombre.text = self.productos[indexPath.row].nombre
cell.marca.text = self.productos[indexPath.row].marca
}
return cell
}
func requestPost () {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.web.es/productos_by_category.php")!)
request.HTTPMethod = "POST"
let postString = "category="+option
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
//println("error=\(error)")
return
}
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
// JSON RESULTADO ENTERO
//println("responseString = \(responseString)")
self.productos = self.parseJsonData(data)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
task.resume()
}
func parseJsonData(data: NSData) -> [Producto] {
var productos = [Producto]()
var error:NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
// Return nil if there is any error
if error != nil {
println(error?.localizedDescription)
}
// Parse JSON data
let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
for jsonProducto in jsonProductos {
let producto = Producto()
producto.nombre = jsonProducto["nombre"] as! String
producto.imagen = jsonProducto["imagen"] as! String
producto.marca = jsonProducto["marca"] as! String
producto.distribuidor = jsonProducto["distribuidor"] as! String
producto.linea = jsonProducto["linea"] as! String
producto.precio = jsonProducto["precio"] as! String
productos.append(producto)
}
return productos
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "verProducto" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let destinationController = segue.destinationViewController as! MarcaProductoViewController
//println(productos[indexPath.row].nombre)
println(indexPath)
destinationController.nombre = productos[indexPath.row].nombre
}
}
}
Thanks in advance,
Regards.
try this way...
if segue.identifier == "verProducto"{
if let indexPath = tableView.indexPathForCell(sender as! BuscarCellTableViewCell){
var detailsVC = segue.destinationViewController as! MarcaProductoViewController
}
}