Confused with UITableViewDataSource Protocol. Conflicts with previous - ios

I have an error that idk how to fix it. The error is: "Definition conflicts with previous value." I have copied the code below and starred the portion which is flagged.
Thanks in advance.
import UIKit
import Parse
class ScienceTableViewController: UITableViewController, UITableViewDataSource {
var dataRecords = [Data]()
override func viewDidLoad() {
super.viewDidLoad()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
dataRecords = [Data]()
let query = PFQuery(className: "data")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
let data = Data(objectID: object.valueForKey("objectId")! as! String, title: object.valueForKey("title")! as! String, date: object.valueForKey("date")! as! String, information: object.valueForKey("information")! as! String)
self.dataRecords.append(data)
self.tableView.reloadData()
}
} else {
print(error)
}
}
}
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 dataRecords.count > 0 ? 1 : 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataRecords.count
}
**override func tableView(tableView: UITableView**, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
let title = dataRecords[indexPath.row].title
let date = dataRecords[indexPath.row].date
let information = dataRecords[indexPath.row].information
cell.textLabel?.text = title
cell.detailTextLabel?.text = date
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller: ViewController = segue.destinationViewController as! ViewController
if segue.identifier == "newData" {
controller.objectID = ""
} else if segue.identifier == "showData" {
let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow!
controller.objectID = dataRecords[indexPath.row].objectID
}
}
}}
I am also getting problems with xCode where it claims "Xcode encountered a problem. Source editor functionality is limited. Attempting to restore" and the editor does not recognize the code for brief moments.

I believe your issue is with the class declaration line that has UITableViewDataSource as a protocol. A UiTableViewController already is a data source so that is redundant and should be removed.

Related

Transformable Swift 3 NSManagedObject type NSAttributedString not working

Subclass of NSManagedObject given below where I have set Managed object type to NSAttributedString.
import Foundation
import CoreData
extension NoteData {
#nonobjc public class func fetchRequest() -> NSFetchRequest<NoteData> {
return NSFetchRequest<NoteData>(entityName: "NoteData")
}
#NSManaged public var image: NSData?
#NSManaged public var note: NSAttributedString?
}
A is my table view controller class where I want to fetch data
import UIKit
import CoreData
class TableViewController: UITableViewController
{
var fetchRequest : NSFetchRequest<NSFetchRequestResult>?
var noteData = [NoteData]()
#IBOutlet var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
load()
table.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
load()
table.reloadData()
}
func load()
{
let fetchRequest : NSFetchRequest <NoteData> = NoteData.fetchRequest()
do
{
let Data = try
databaseController.getContext().fetch(fetchRequest)
self.table.reloadData()
noteData = Data
}
catch
{
print("Error . \(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return noteData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell:UITableViewCell = UITableViewCell()
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let NoteData = noteData[indexPath.row]
NoteData.note?.setValue("hello", forKey: "mykey")
print ("\( cell.textLabel?.attributedText = NoteData.note?.value(forKey: "mykey") as! NSAttributedString)")
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showItem"{
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPath(for: cell)
let itemController : mainViewController = segue.destination as! mainViewController
itemController.noteData = noteData[(indexPath?.row)!]
}
if segue.identifier == "showItem"{
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPath(for: cell)
let itemController : mainViewController = segue.destination as! mainViewController
itemController.noteData = noteData[(indexPath?.row)!]
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let target = noteData[indexPath.row]
databaseController.persistentContainer.viewContext.delete(target)
databaseController.saveContext()
load()
table.reloadData()
}
}
But I am getting error after doing everything The error is here :

Parse Swift UITableView Accessory

I have the following code, and now I am trying to implement accessory to the UITableView.
All the data is from Parse, even though there are tutorials out there helping out on how to do normal accessory, I am unable to find one that actually teaches on how to do that if I am getting data from online db like Parse.
//
// Listdoctors.swift
// ihealthtwo
//
// Created by David on 10/1/16.
// Copyright © 2016 ƒ. All rights reserved.
//
import UIKit
import Parse
class Listdoctors: UITableViewController {
#IBOutlet var listdoctors: UITableView!
var doctorName = [String]()
var doctorRate = [NSInteger]()
var doctorDetail = [String]()
var refresher: UIRefreshControl!
func refresh()
{
let query = PFQuery(className: "doctors")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock(
{
(listll: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(listll!.count) names of the lawyers.")
// Do something with the found objects
if let objects = listll {
for object in objects {
print(object)
self.doctorName.append(object["doctorName"] as! String)
self.doctorRate.append(object["Rate"] as! NSInteger)
self.doctorDetail.append(object["doctorContent"] as! String)
// print(object["Lawyer_Name"] as! String )
// self.lawyersname.append(object["Lawyer_Name"] as! String)
//self.lblName.text = object["Lawyer_Name"] as? String
}
self.listdoctors.reloadData()
}
print(self.doctorName.count)
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
self.tableView.reloadData()
self.refresher.endRefreshing()
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refrehsh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(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 doctorName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let doctorcell: doctorsCell = tableView.dequeueReusableCellWithIdentifier("doctorsproto") as! doctorsCell
// Configure the cell...
doctorcell.doctorname.text = doctorName[indexPath.row]
doctorcell.doctorcontent.text = doctorDetail[indexPath.row]
doctorcell.doctorrate.text = "\(doctorRate [indexPath.row])"
//lawyercell.lblExpll.text = lawyerExp[indexPath.row]
//lawyercell.lblPracareall.text = lawyerPracArea[indexPath.row]
//profImages[indexPath.row].getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
// if imageData != nil {
// let image = UIImage(data: imageData!)
// lawyercell.imageLawyer.image = image
// }
// else
// {
// print(error)
// } }
return doctorcell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
}
// MARK: - Navigation to doctor detail
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier
{
switch identifier
{
doctor "TodoctorDetail":
let productDetailVC = segue.destinationViewController as! doctorDetail
if let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)
{
}
default: break
}
}ˍ
}
//MARK: - Helper Method
//func productAtIndexPath(indexPath: NSIndexPath) ->?? (waht should i Put here)
}
My last line of code is not what I am sure what I exactly need to return, this is a example I am following from
https://www.youtube.com/watch?v=c-E_EbMR9wA
From the looks of it, you're trying to pass your data to a detail view which in this case you should be doing something like this assuming you have the proper indexPath and variables defined in the detailView already.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier
{
switch identifier
{
doctor "TodoctorDetail":
let productDetailVC = segue.destinationViewController as! doctorDetail
if let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)
{
// Assuming you have the proper indexPath defined here for the selected cell and that you have these three values already defined in your productDetailVC
productDetailVC.doctorName = doctorName[indexPath.row]
productDetailVC.doctorContent = doctorContent[indexPath.row]
productDetailVC.doctorRate = doctorRating[indexPath.row]
}
default: break
}
}ˍ
}

SWIFT: Difficultly displaying data in tableView

I am attempting to display data from Parse onto the following tableView controller. For some reason, the data is not displaying on the tableView (i.e. the rows are blank). I do not think that the data queried from Parse is being appended to the arrays. I am wondering what I'm doing wrong here.
Here's the current output:
I am using a custom prototype cell with identifier "CellTrack" class "TrackTableViewCell" and as shown below:
Here is my code in the TableViewController file:
import UIKit
import Parse
class MusicPlaylistTableViewController: UITableViewController {
var usernames = [String]()
var songs = [String]()
var dates = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
var query = PFQuery(className:"PlaylistData")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects! as? [PFObject] {
self.usernames.removeAll()
self.songs.removeAll()
self.dates.removeAll()
for object in objects {
let username = object["username"] as? String
self.usernames.append(username!)
print("added username")
let track = object["song"] as? String
self.songs.append(track!)
let date = object["createdAt"] as? String
self.dates.append(date!)
self.tableView.reloadData()
}
}
} else {
print(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(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 usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellTrack", forIndexPath: indexPath) as! TrackTableViewCell
cell.username.text = usernames[indexPath.row]
cell.songTitle.text = songs[indexPath.row]
cell.CreatedOn.text = dates[indexPath.row]
return cell
}
}
And here is my code in the "TrackTableViewCell.swift" class:
import UIKit
class TrackTableViewCell: UITableViewCell {
#IBOutlet weak var songTitle: UILabel!
#IBOutlet weak var username: UILabel!
#IBOutlet weak var CreatedOn: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Execute your tableView.reloadData() in main thread.
dispatch_async(dispatch_get_main_queue(), {
self.tableViewCell.reloadData()
})
Try doing a guard let to see if those values are actually coming back as string or not. My guess would be that the value for created at never came back. Try it out and let me know.
guard let username = object["username"] as? String else {
print ("could not get username")
}
self.usernames.append(username)
print("added username")
guard let track = object["song"] as? String else {
print ("could not get song")
return
}
self.songs.append(track)
guard let date = object["createdAt"] as? String else {
print ("could not get createdAt")
return}
self.dates.append(date!)
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell?
Return Value
A UITableViewCell object with the associated identifier or nil if no such object exists in the reusable-cell queue.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CellTrack", forIndexPath: indexPath) as! TrackTableViewCell
if cell == nil {
// create a new cell here
cell = TrackTableViewCell(...)
}
cell.username.text = usernames[indexPath.row]
cell.songTitle.text = songs[indexPath.row]
cell.CreatedOn.text = dates[indexPath.row]
return cell
}

Can someone help me delete a table view cell?

Can someone help me delete a table view cell. I would like to be able to swipe left and have a delete option. Sorry, I know this is simple but I'm still learning how to code. I am using Parse. Thank you!
import UIKit
class MasterTableViewController: UITableViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {
var noteObjects: NSMutableArray! = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (PFUser.currentUser() == nil) {
}else {
self.fetchAllObjectsFromLocalDatastore()
self.fetchAllObjects()
}
}
func fetchAllObjectsFromLocalDatastore() {
var query: PFQuery = PFQuery(className: "Note")
query.fromLocalDatastore()
query.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil) {
var temp: NSArray = objects!; NSArray.self
self.noteObjects = temp.mutableCopy() as! NSMutableArray
self.tableView.reloadData()
}else {
}
}
}
func fetchAllObjects() {
PFObject.unpinAllObjectsInBackgroundWithBlock(nil)
var query: PFQuery = PFQuery(className: "Note")
query.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil) {
PFObject.pinAllInBackground(objects, block: { (success, error) in
if error == nil {
self.fetchAllObjectsFromLocalDatastore()
}
})
}else {
println(error!.userInfo)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.noteObjects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MasterTableViewCell
var object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
cell.masterTitleLabel?.text = object["title"] as? String
cell.masterTextLabel?.text = object["text"] as? String
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("editNote", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var upcoming: AddNoteTableViewController = segue.destinationViewController as! AddNoteTableViewController
if (segue.identifier == "editNote") {
let indexPath = self.tableView.indexPathForSelectedRow()!
var object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
upcoming.object = object
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
}
use this code
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
langData.removeAtIndex(indexPath.row) //langData is array from i delete values
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
hope it may help you for more visit here

How can I run prepareForSegue After didSelectRowAtIndexPath?

I'm trying to get the indexPath.row that user clicked and then check with my array to return a String from that indexPath.row and then send the String via preparforSegue.... But it doesnt work. I think the program runs the preparForSegue BEFORE the didselectRowatIndexPath... How can I do this?
My Code:
import UIKit
import Parse
class CategoriaTableViewController: UITableViewController {
var queryArray: [PFObject] = [PFObject]()
var escolha = 5
override func viewDidLoad() {
super.viewDidLoad()
var query = PFQuery(className:"Categorias")
//querycomlocalidade
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
println("Successfully retrieved \(objects!.count) Restaurantes.")
if let _objects = objects as? [PFObject] {
self.queryArray = _objects
self.tableView.reloadData()
}
} else {
println("Error: \(error!) \(error!.userInfo!)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return queryArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CategoriaTableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ceculaCategoria", forIndexPath: indexPath) as! CategoriaTableViewCell
let categoria = queryArray[indexPath.row] as! PFObject
//Insere texto
cell.tituloCecula.text = categoria.objectForKey("nome") as! String
//Insere imagens no tableview
if let categoriaImagem = categoria.objectForKey("imagem") as? PFFile {
categoriaImagem.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if (error == nil) {
cell.imagemCecula.image = UIImage(data:imageData!) }
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
escolha = indexPath.row
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var detailScene = segue.destinationViewController as! ListaTableViewController
if let indexPath = self.tableView.indexPathForSelectedRow() {
let row = Int(indexPath.row)
let categoriaEscolhida = queryArray[escolha] as PFObject
//Insere texto
detailScene.categoria = categoriaEscolhida.objectForKey("nome") as! String
}
}
}
If you have linked the segue directly from your cell in the storyboard then didSelectRowAtIndexPath will not execute before the segue is triggered.
What you can do is create a segue by Ctrl-dragging from the view controller object in the storyboard to the destination scene and giving the segue an identifier as you would with any other segue. Delete the segue from your cell.
Now you can call performSegueWithIdentifier to trigger the segue and pass the object that was selected as the sender
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// tableView.deselectRowAtIndexPath(indexPath) // Optionally deselect the row for a cleaner appearance
self.performSegueWithIdentifier("mySegueIdentifier", sender: queryArray[indexPath.row])
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let detailScene = segue.destinationViewController as? ListaTableViewController {
let categoriaEscolhida = sender as! PFObject
detailScene.categoria = categoriaEscolhida.objectForKey("nome") as! String
}
}
You need to create the segue between the two view controllers and trigger it manually:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
escolha = indexPath.row
self.performSegueWithIdentifier("push", sender: self)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
escolha = indexPath.row
self.performSegueWithIdentifier("push", sender: self)
}
Complete with ...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:"push"]) {
// Code
}

Resources