tableView.reloadData() causing a crash of the app - swift

In the Swift app, I present an addition view to add an element to the CoreData database. If I call tableview.reloadData(), the app crashes on the + button on the main screen. If I omit the reload data then the add view is presented and the data is added to the CoreData file.
the main view, from configureCell down:
func configureCell(cell: TransectTableViewCell, indexPath:NSIndexPath) {
let transectEntry = fetchedResultController.objectAtIndexPath(indexPath) as! Transects
cell.transectNameLabel.text = transectEntry.transectName
cell.transectNameLabel.textColor = UIColor.blackColor()
cell.transectNameLabel.shadowColor = UIColor.whiteColor()
cell.transectNameLabel.shadowOffset = CGSizeMake(1, 1)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let countEntry = fetchedResultController.objectAtIndexPath(indexPath) as! Transects
coreDataStack.context.deleteObject(countEntry)
coreDataStack.saveContext()
}
}
func tableView(tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath)
-> CGFloat {
return 50;
}
func didFinishViewController(viewController: AddTransectViewController, didSave: Bool) {
if didSave {
var error: NSError? = nil
let context = viewController.context
self.coreDataStack.saveContext()
}
dismissViewControllerAnimated(true, completion: {})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "addTransectSegue" {
let newTransectViewController = segue.destinationViewController as! AddTransectViewController
let transectEntryEntity = NSEntityDescription.entityForName("Transects", inManagedObjectContext: coreDataStack.context)
let newTransectEntry = Transects(entity: transectEntryEntity!, insertIntoManagedObjectContext: coreDataStack.context)
newTransectViewController.transectNewEntry = newTransectEntry
newTransectViewController.context = newTransectEntry.managedObjectContext
newTransectViewController.delegate = self
}
if segue.identifier == "transectTasksSegue" {
let indexPath = tableView.indexPathForSelectedRow()!
let transectSelected = fetchedResultController.objectAtIndexPath(indexPath) as! Transects
let tasksViewController = segue.destinationViewController as! TransectTasksViewController
tasksViewController.coreDataStack = coreDataStack
tasksViewController.selectedTransect = transectSelected
}
}
func controllerDidChangeContent(controller:
NSFetchedResultsController) {
tableView.reloadData()
}
The addition view is:
import UIKit
import CoreData
import Foundation
protocol TransectDelegate {
func didFinishViewController(ViewController:AddTransectViewController, didSave:Bool)
}
class AddTransectViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var transectNameTextField: UITextField!
#IBOutlet weak var latitudeTextField: UITextField!
#IBOutlet weak var longitudeTextField: UITextField!
#IBOutlet weak var altitudeTextField: UITextField!
var transectNewEntry: Transects!
var context: NSManagedObjectContext!
var delegate:TransectDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func updateTransectEntry() {
if let entry = transectNewEntry {
entry.transectName = transectNameTextField.text
entry.latitude = latitudeTextField.text
entry.longitude = longitudeTextField.text
entry.altitude = altitudeTextField.text
}
}
#IBAction func cancelButtonWasTapped(sender: AnyObject) {
delegate?.didFinishViewController(self, didSave: false)
}
#IBAction func saveButtonWasTapped(sender: AnyObject) {
updateTransectEntry()
delegate?.didFinishViewController(self, didSave: true)
}
}
I am missing something, but cannot see what. Ideas would be welcome.
The app hangs up on cell.transectNameLabel.text = transectEntry.transectName
with: Thread 1:EXC_BAD_ACCESS (code=1, address=0x0)
My real confusion is that this works perfectly:
import UIKit
import CoreData
class PlantSpeciesViewController: UIViewController, NSFetchedResultsControllerDelegate, PlantSpeciesDelegate, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView:UITableView!
var coreDataStack: CoreDataStack!
lazy var fetchedResultController:
NSFetchedResultsController = self.plantSpeciesFetchedResultsController()
var plantSpecies: PlantSpecies!
var selectedFamily: PlantFamily!
var context: NSManagedObjectContext!
var plantFamilyName: String!
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.clearColor()
view.backgroundColor = UIColor(patternImage: UIImage (named: "Monitor backdrop.png")!)
self.title = plantFamilyName
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func plantSpeciesFetchedResultsController()
->NSFetchedResultsController {
fetchedResultController =
NSFetchedResultsController(
fetchRequest: plantSpeciesFetchRequest(),
managedObjectContext: coreDataStack.context,
sectionNameKeyPath: nil,
cacheName: nil)
fetchedResultController.delegate = self
var error: NSError? = nil
if (!fetchedResultController.performFetch(&error)){
println("Error: \(error?.localizedDescription)")
abort()
}
return fetchedResultController
}
func plantSpeciesFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "PlantSpecies")
fetchRequest.fetchBatchSize = 20
let predicate = NSPredicate(format: "familyName == %#", selectedFamily)
fetchRequest.predicate = predicate
let sortDescriptor = NSSortDescriptor(key: "plantSpecies", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
//var error: NSError?
return fetchRequest
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultController.sections!.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultController.sections![section].numberOfObjects
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("plantSpeciesCell", forIndexPath: indexPath) as! PlantSpeciesTableViewCell
cell.backgroundColor = UIColor.clearColor()
configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(cell: PlantSpeciesTableViewCell, indexPath:NSIndexPath) {
let plantEntry = fetchedResultController.objectAtIndexPath(indexPath) as! PlantSpecies
cell.speciesNameLabel.text = plantEntry.plantSpecies
cell.speciesNameLabel.textColor = UIColor.blackColor()
cell.speciesNameLabel.shadowColor = UIColor.whiteColor()
cell.speciesNameLabel.shadowOffset = CGSizeMake(1, 1)
cell.speciesImageView.image = UIImage (data: plantEntry.plantImage)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let countEntry = fetchedResultController.objectAtIndexPath(indexPath) as! PlantFamily
coreDataStack.context.deleteObject(countEntry)
coreDataStack.saveContext()
}
}
func tableView(tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath)
-> CGFloat {
return 90;
}
func didFinishViewController(viewController: AddPlantSpeciesViewController, didSave: Bool) {
if didSave {
var error: NSError? = nil
let context = viewController.context
self.coreDataStack.saveContext()
}
dismissViewControllerAnimated(true, completion: {})
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "addSpeciesSegue" {
let newPlantViewController = segue.destinationViewController as! AddPlantSpeciesViewController
let plantEntryEntity = NSEntityDescription.entityForName("PlantSpecies", inManagedObjectContext: coreDataStack.context)
let newSpeciesEntry = PlantSpecies(entity: plantEntryEntity!, insertIntoManagedObjectContext: coreDataStack.context)
newPlantViewController.selectedFamily = selectedFamily
newPlantViewController.plantNameEntry = newSpeciesEntry
newPlantViewController.context = newSpeciesEntry.managedObjectContext
newPlantViewController.delegate = self
}
}
func controllerDidChangeContent(controller:
NSFetchedResultsController) {
tableView.reloadData()
}
}
coupled with:
import UIKit
import CoreData
import Foundation
protocol PlantSpeciesDelegate {
func didFinishViewController(ViewController:AddPlantSpeciesViewController, didSave:Bool)
}
class AddPlantSpeciesViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var plantNameTextField: UITextField!
#IBOutlet weak var plantImageView: UIImageView!
#IBOutlet weak var imageSwitch: UISwitch!
#IBOutlet weak var imageFromFileButton: UIButton!
#IBOutlet weak var imageFromCameraButton: UIButton!
let imagePicker = UIImagePickerController()
var plantNameEntry: PlantSpecies!
var selectedFamily: PlantFamily!
var passedPlantFamily: String!
var newPlantName: String!
var newImageData: NSData!
var context: NSManagedObjectContext!
var delegate:PlantSpeciesDelegate?
override func viewDidLoad() {
super.viewDidLoad()
plantImageView.image = UIImage(named: "placeholder image.jpg")
imagePicker.delegate = self
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func imageSourceSwitch(sender: AnyObject) {
if imageSwitch.on == true
{
self.imageFromFileButton.enabled = true
self.imageFromCameraButton.enabled = false
}
else
{
self.imageFromCameraButton.enabled = true
self.imageFromFileButton.enabled = false
}
}
#IBAction func imageFromFile(sender: AnyObject) {
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func imageFromCamera(sender: AnyObject) {
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.plantImageView.image = image
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func getPlantName() {
newPlantName = plantNameTextField.text
plantNameTextField.resignFirstResponder()
}
func updateSpeciesEntry() {
if let entry = plantNameEntry {
entry.plantSpecies = newPlantName
entry.plantImage = UIImageJPEGRepresentation(plantImageView.image, 1.0)
entry.familyName = selectedFamily
}
}
#IBAction func cancelButtonWasTapped(sender: AnyObject) {
delegate?.didFinishViewController(self, didSave: false)
}
#IBAction func saveButtonWasTapped(sender: AnyObject) {
updateSpeciesEntry()
delegate?.didFinishViewController(self, didSave: true)
}
}
So, what is the difference?

This happen to me too, fixed it with:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
instead of just tableView.reloadData()
, cause it seems that it was being called from wrong thread.

The reason for the crash is most likely that the table cannot load the data, for example a value does not exist and is being force unwrapped. The crash only happens, therefore, when you try to collect the data. Check through all the values to be sure.

I'd like to expand on GJZ answer & what brought me here. I have UITableViewCells that have a textfield. I attempted to get values the user entered from the field.
let companyNameCell: TextEntryCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! TextEntryCell
what I realized is that when I dynamically hide and showed rows by changing the cell heights using the tableview.reloadrows method, the app would crash if it attempted to read a cell the user could not see on their screen. that is because the cells I think were deallocated.

Related

unabe to Reload data in tableview via userdefault

I am a newbie and learning ios programming. I have made a custom table view cell. I am trying to append data in it via user defaults but its not storing the data, every time i go back the app refreshes making the table view blank screen.
// data sent from here
class ViewController: UIViewController {
#IBOutlet weak var textfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func submit(_ sender: AnyObject) {
performSegue(withIdentifier: "move", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as? secondviewcontroller
destination?.list.append(textfield.text!)
let defaults = UserDefaults.standard
defaults.set(destination?.list, forKey: "listarray")
UserDefaults.standard.synchronize()
}
}
// here i want to retreive
class secondviewcontroller: UIViewController {
#IBOutlet weak var tblView: UITableView!
var list = ["fahad","Ali","tahir"]
var abc = ""
override func viewDidLoad() {
super.viewDidLoad()
tblView.dataSource = self;
tblView.delegate = self;
let storedarray = UserDefaults.standard.object(forKey: "listarray")
print("hi\(storedarray)")
}
override func viewDidAppear(_ animated: Bool) {
tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
tblView.reloadData()
}
#IBAction func backbtn(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
import UIKit
class secondviewcontroller: UIViewController {
#IBOutlet weak var tblView: UITableView!
var list = ["fahad","Ali","tahir"]
var abc = ""
override func viewDidLoad() {
super.viewDidLoad()
tblView.dataSource = self;
tblView.delegate = self;
}
override func viewDidAppear(_ animated: Bool) {
tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
let storedarray = UserDefaults.standard.object(forKey: "listarray")
print("hi\(storedarray)")
tblView.reloadData()
}
#IBAction func backbtn(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
extension secondviewcontroller : UITableViewDataSource , UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print (list)
return list.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell;
cell.textlabel.text = list[indexPath.row];
return cell;
}
}
// my custom table view
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var textlabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
My UI storyboardgetting this error
you must subclass the UITableViewDelegate and UITableViewDataSource methods and implement the required methods for it to display the data in your custom view.
refer to this: http://clean-swift.com/refactoring-table-view-data-source-and-delegate-methods/
try adding the code for stored array into the viewwillappear method..
These lines recreates the same list with an new element without considering the saved items:
destination?.list.append(textfield.text!)
let defaults = UserDefaults.standard
defaults.set(destination?.list, forKey: "listarray")
UserDefaults.standard.synchronize()
You should instead:
let newEntry = textfield.text!
let defaults = UserDefaults.standard
if destination?.list.count == 3 { //3 because you hardcoded 3 items in next controller
destination?.list.append(newEntry)
} else {
let obj = defaults.object(forKey: "listarray") as? [String] ?? [String]()
destination?.list = obj.append(newEntry)
}
defaults.set(destination?.list, forKey: "listarray")
UserDefaults.standard.synchronize()

CoreData not Persisting?

I am saving an exercise into core data and calling it into the table, this works in terms of carrying the info from the user input into the table, however the coredata doesnt persist so when i re open the app, the entry is lost.
It was actually working yesterday and seems to have broken, but I havent made a change that would effect this as far as im aware. The one thing i found when debugging is that when I loaded the app its meant to point at the sql database in my console, however its changed to a .configurationprofiles file? Could this be a cause and what would the fix be? I will include the code for the tableview and the code for the user entry form below to show the information flow. Let me know if any other data is needed to be added.
import Foundation
import UIKit
import CoreData
class ExerciseEditorController: UIViewController, UITextFieldDelegate {
var managedObjectContext: NSManagedObjectContext?
var userRepsCount = Int()
var userSetsCount = Int()
#IBOutlet weak var userExerciseName: UITextField!
#IBOutlet weak var userExerciseSetCounter: UILabel!
#IBOutlet weak var userExerciseRepsCounter: UILabel!
#IBOutlet weak var userExerciseWeight: UITextField!
#IBAction func userSetsStepper(_ sender: UIStepper) {
userExerciseSetCounter.text = Int(sender.value).description
self.userSetsCount = Int(sender.value)
}
#IBAction func userRepsStepper(_ sender: UIStepper) {
userExerciseRepsCounter.text = Int(sender.value).description
self.userRepsCount = Int(sender.value)
}
#IBAction func cancelExerciseEditor(_ sender: Any) {
self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self)
}
#IBAction func saveExerciseToWorkout(_ sender: Any) {
createExercise()
self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = (UIColor.customBackgroundGraphite())
userExerciseSetCounter.text = String(userSetsCount)
userExerciseRepsCounter.text = String(userSetsCount)
userExerciseWeight.delegate = self
userExerciseWeight.keyboardType = .numbersAndPunctuation
}
func createExercise() {
let userExerciseWeightSet = Double(self.userExerciseWeight.text!) //make this safe!
guard let managedObjectContext = managedObjectContext else { return }
let userExercise = UserExercise(context: managedObjectContext)
userExercise.name = userExerciseName.text
userExercise.sets = Int64(userSetsCount)
userExercise.reps = Int64(userRepsCount)
userExercise.weight = userExerciseWeightSet! //make this safe!
userExercise.createdAt = Date().timeIntervalSince1970
}
func animateTextField(textField: UITextField, up: Bool) {
let movementDistance:CGFloat = -130
let movementDuration: Double = 0.3
var movement:CGFloat = 0
if up {
movement = movementDistance
}
else {
movement = -movementDistance
}
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.animateTextField(textField: textField, up:true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.animateTextField(textField: textField, up:false)
}
}
And this is the tableview:
import Foundation
import UIKit
import CoreData
class WorkoutDesignerController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
#IBAction func unwindToWorkoutDesigner(segue: UIStoryboardSegue) {}
#IBOutlet weak var workoutDesignerTable: UITableView!
#IBOutlet weak var tapToAddExercise: UILabel!
#IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
#IBAction func cancelWorkoutDesigner(_ sender: Any) {
self.performSegue(withIdentifier: "unwindToTemplatesWithSegue", sender: self)
}
private let persistentContainer = NSPersistentContainer(name: "Lift")
override func viewDidLoad() {
super.viewDidLoad()
setupView()
workoutDesignerTable.delegate = self
workoutDesignerTable.dataSource = self
view.backgroundColor = (UIColor.customBackgroundGraphite())
persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
if let error = error {
print("Unable to Load Persistent Store")
print("\(error), \(error.localizedDescription)")
} else {
self.setupView()
do {
try self.fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("Unable to Perform Fetch Request")
print("\(fetchError), \(fetchError.localizedDescription)")
}
self.updateView()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let userExercises = fetchedResultsController.fetchedObjects else { return 0 }
return userExercises.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? RoutineTableViewCell else {
fatalError("Unexpected Index Path")
}
cell.backgroundColor = UIColor.customBackgroundGraphite()
cell.textLabel?.textColor = UIColor.white
let userExercise = fetchedResultsController.object(at: indexPath)
cell.nameLabel.text = userExercise.name
cell.repsLabel.text = String(userExercise.reps)
cell.setsLabel.text = String(userExercise.sets)
cell.weightLabel.text = String(userExercise.weight)
return cell
}
private func setupView() {
setupMessageLabel()
updateView()
}
private func setupMessageLabel() {
tapToAddExercise.text = "Tap + To Add An Exercise To The Routine"
}
fileprivate func updateView() {
var hasUserExercises = false
if let UserExercise = fetchedResultsController.fetchedObjects {
hasUserExercises = UserExercise.count > 0
}
workoutDesignerTable.isHidden = !hasUserExercises
tapToAddExercise.isHidden = hasUserExercises
activityIndicatorView.stopAnimating()
}
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<UserExercise> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<UserExercise> = UserExercise.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addNewExerciseSegue" {
if let destinationViewController = segue.destination as? ExerciseEditorController {
// Configure View Controller
destinationViewController.managedObjectContext = persistentContainer.viewContext
}
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
workoutDesignerTable.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
workoutDesignerTable.endUpdates()
updateView()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
workoutDesignerTable.insertRows(at: [indexPath], with: .fade)
}
break;
default:
print("...")
}
}
}
You need to call context.save().

Difficulties in moving Page in swift

when I select UIButoon(selectMaghsad or selectMabda) go AircraftSearch to SelectedCity without difficulty and problem I choose one cell in selecteCity(tableviewController) go back to AircraftSearch and show data in label (labelcity) The problem is that Without that I want again go to tableViewController(selecteCity)
and alert :
A
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7f867b5a4920 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}}
why ??
Where do you think the problem is?
can you help me ??
AircraftSearch
class AircraftSearch: UIViewController ,SendbackDelegate{
#IBOutlet weak var Mabda: UIButton!
#IBOutlet weak var maghsad: UIButton!
#IBOutlet weak var labelcity: UILabel!
#IBOutlet weak var cityTectfield: UITextField!
var Airurl = NSURL()
var ScrOrDstArray = [MabdaAndMaghsad]()
var origin = [String]() // save mabda
var purpose = [String]() // save maghsad
var sendDataToTableview = [String]()
var tit = String()
override func viewDidLoad() {
super.viewDidLoad()
labelcity.text = tit
GetPassCity()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectMabda(sender: AnyObject) {
sendDataToTableview = origin
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
#IBAction func selectMaghsad(sender: AnyObject) {
sendDataToTableview = purpose
print(sendDataToTableview)
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
func originAndpurpose() {
let dataCity = ScrOrDstArray
for i in dataCity{
if i.SrcOrDst == true{
origin.append(i.Name)
}else{
purpose.append(i.Name)
}
}
}
func GetPassCity(){
let actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView
actInd.center = self.view.center
actInd.hidesWhenStopped = true
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(actInd)
actInd.startAnimating()
NSURLSession.sharedSession().dataTaskWithURL(Airurl){ ( data ,response ,error) in
if error != nil{
print("A")
print(error!)
}else{
do{
//readin data from Server
let posts = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
//save data
for post in posts{
var postCity:MabdaAndMaghsad?
if let Id = post["Id"] as? Int ,
let nameCity = post["Name"] as? String ,
let SrcOrDst = post["SrcOrDst"] as? Bool
{
postCity = MabdaAndMaghsad(ID: Id, Name: nameCity, SrcOrDst: SrcOrDst)
}
self.ScrOrDstArray.append(postCity!)
}
//===============
dispatch_async(dispatch_get_main_queue()){
actInd.stopAnimating()
self.originAndpurpose()
print(self.origin)
print("=======")
// print(self.purpose)
}
}catch let error as NSError{
print("B")
print(error)
}
}
}.resume()
}
func sendNameToPreviousVC(SelectCity: String) {
tit = SelectCity
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectedCellSegue" {
if let VC = segue.destinationViewController as? SelectedCity {
VC.toTake = sendDataToTableview
VC.delegate = self
}
}
}
}
SelectedCity view
import UIKit
protocol SendbackDelegate:class {
func sendNameToPreviousVC(City:String)
}
class SelectedCity: UITableViewController {
var toTake = [String]()
var selecteCity = String()
weak var delegate: SendbackDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
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 toTake.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("stcell", forIndexPath: indexPath) as? mAndMCell
let nameCity = toTake[indexPath.row]
print(nameCity)
cell!.nameCityLabel.text = nameCity
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! mAndMCell!
selecteCity = currentCell.nameCityLabel!.text as String!
sendBackIdCity(selecteCity)
navigationController?.popViewControllerAnimated(true)
}
func sendBackIdCity(name: String){
self.delegate?.sendNameToPreviousVC(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "backCitySegue"{
var VCOne = segue.destinationViewController as? AircraftSearch
self.delegate = VCOne
}
}
}
pic

How to pass data to AddController to UITableViewController

I have a problem with my swift code. I have an UITableViewCotroller with a prototype cell, in this cell there are three labels. I created the file TimerCell.swift with the #IBOutlet for the labels:
import UIKit
class TimerCell: UITableViewCell {
#IBOutlet var circostanza: UILabel!
#IBOutlet var luogo: UILabel!
#IBOutlet var tempo: 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
}
}
and the file TimerModel.swift with this code:
import UIKit
class TimerModel: NSObject, NSCoding {
var circostanza :String!
var luogo : String!
var tempo : String!
init(circostanzaIn:String, luogoIn:String, tempoIn:String) {
circostanza = circostanzaIn
luogo = luogoIn
tempo = tempoIn
}
internal required init(coder aDecoder: NSCoder) {
self.circostanza = aDecoder.decodeObjectForKey("circostanza") as! String
self.luogo = aDecoder.decodeObjectForKey("luogo") as! String
self.tempo = aDecoder.decodeObjectForKey("tempo") as! String
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(self.circostanza, forKey: "circostanza")
encoder.encodeObject(self.luogo, forKey: "luogo")
encoder.encodeObject(self.tempo, forKey: "tempo")
}
}
Then I have a button + in the UITableViewCotroller to open an AddController with three text field to add some data. I want to save these data in the cell's labels. The code in the AddController is:
import UIKit
class AddTimerController: UIViewController, UITextFieldDelegate {
#IBOutlet var fieldCircostanza: UITextField!
#IBOutlet var fieldLuogo: UITextField!
#IBOutlet var fieldTempo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
fieldCircostanza.delegate = self
fieldLuogo.delegate = self
//
var keyboardToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 44))
keyboardToolbar.barStyle = UIBarStyle.BlackTranslucent
keyboardToolbar.backgroundColor = UIColor.redColor()
keyboardToolbar.tintColor = UIColor.whiteColor()
var flex = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var save = UIBarButtonItem(title: "Fatto", style: UIBarButtonItemStyle.Done, target: fieldTempo, action: "resignFirstResponder")
keyboardToolbar.setItems([flex, save], animated: false)
fieldTempo.inputAccessoryView = keyboardToolbar
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder() // chiudere la tastiera nei campi di testo
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func annulla(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil) // chiude una modal
}
#IBAction func salva(sender: UIButton) {
if fieldCircostanza.text.isEmpty &&
fieldLuogo.text.isEmpty &&
fieldTempo.text.isEmpty{
//alertView
return
}
var timer = TimerModel(circostanzaIn: fieldCircostanza.text,
luogoIn: fieldLuogo.text,
tempoIn: fieldTempo.text)
DataManager.sharedInstance.salvaArray()
DataManager.sharedInstance.detail.myCollection.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
}
Finally the UITableViewCotroller file:
import UIKit
class TimerViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
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 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataManager.sharedInstance.storage.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TimerCell
//cell.circostanza.text = timer.circostanza
//cell.luogo.text = timer.luogo
//cell.tempo.text = timer.tempo
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
DataManager.sharedInstance.storage.removeAtIndex(indexPath.row)
DataManager.sharedInstance.salvaArray()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// MARK: - Navigazione
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "modifica" {
//let controller = (segue.destinationViewController as UINavigationController).topViewController as AddController
}
}
}
Can you help me with the code for saving data?
for your query in the comment, this will correct that:
In your TimerModel:
import UIKit
class TimerModel: NSObject, NSCoding {
var circostanza :String!
var luogo : String!
var tempo : String!
override init() { // add this method
super.init()
}
init(circostanzaIn:String, luogoIn:String, tempoIn:String) {
circostanza = circostanzaIn
luogo = luogoIn
tempo = tempoIn
}
internal required init(coder aDecoder: NSCoder) {
self.circostanza = aDecoder.decodeObjectForKey("circostanza") as! String
self.luogo = aDecoder.decodeObjectForKey("luogo") as! String
self.tempo = aDecoder.decodeObjectForKey("tempo") as! String
}
func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(self.circostanza, forKey: "circostanza")
encoder.encodeObject(self.luogo, forKey: "luogo")
encoder.encodeObject(self.tempo, forKey: "tempo")
}
}
For accessing timer in tableViewController, do this:
import UIKit
class AddTimerController: UIViewController, UITextFieldDelegate {
#IBOutlet var fieldCircostanza: UITextField!
#IBOutlet var fieldLuogo: UITextField!
#IBOutlet var fieldTempo: UITextField!
var timer: TimerModel! // Made timer a class member
override func viewDidLoad() {
......
}
// your code ....
#IBAction func salva(sender: UIButton) {
if fieldCircostanza.text.isEmpty &&
fieldLuogo.text.isEmpty &&
fieldTempo.text.isEmpty{
//alertView
return
}
timer = TimerModel(circostanzaIn: fieldCircostanza.text, // intialize timer
luogoIn: fieldLuogo.text,
tempoIn: fieldTempo.text)
DataManager.sharedInstance.salvaArray()
DataManager.sharedInstance.detail.myCollection.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
}
and after that in tableViewController, access it like this:
class TimerViewController: UITableViewController {
var timer: TimerModel! // Change to this
override func viewDidLoad() {
super.viewDidLoad()
var controller : AddTimerController = AddTimerController()
timer = controller.timer
}
// your code .......
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TimerCell
cell.circostanza.text = timer.circostanza
cell.luogo.text = timer.luogo
cell.tempo.text = timer.tempo
return cell
}
}

Delegating a string to a UILabel and an image to a UIImageView - Swift

So, this is what's happening: I have two controllers; MainViewController and DetailsTableViewController. On DetailsTableViewController I want to write a name for random recipe, then I pick an image from photo library. After that, I want to send those data to a cell in MainViewController. The code this:
import UIKit
import CoreData
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, sendDetailsToMVCDelegate {
#IBOutlet weak var mainImage: UIImageView!
#IBOutlet weak var tableView: UITableView!
var namesListArray: [String] = []
var imagesListArray: [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func sendDetailsToMVC (name: String, image: UIImage) {
namesListArray.append(name)
imagesListArray.append(image)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesListArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var row = indexPath.row
var name: String = namesListArray[row] as String
var image: UIImage = imagesListArray[row] as UIImage
var cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as! CustomCellTableViewCell
cell.customLabel!.text = (name as String)
cell.customImage.image = (image as UIImage)
return cell
}
}
and
import UIKit
import CoreData
protocol sendDetailsToMVCDelegate {
func sendDetailsToMVC(name: String, image: UIImage)
}
class DetailsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, sendNameToDetailsViewControllerDelegate {
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var recipeImage: UIImageView!
#IBOutlet weak var tableView: UITableView!
var ingredientsList = [""]
var delegateDetails: sendDetailsToMVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
let howToDoButton = UIBarButtonItem(title:"How To Do", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showHowToDoScreen"))
navigationItem.rightBarButtonItem = howToDoButton
let newIngredientButton = UIBarButtonItem(title:"New Ingredient", style: UIBarButtonItemStyle.Plain, target:self, action: Selector("showNewIngredientScreen"))
navigationItem.leftBarButtonItem = newIngredientButton
//Picker imagem pelo toque
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
tapGestureRecognizer.numberOfTapsRequired = 1
recipeImage.addGestureRecognizer(tapGestureRecognizer)
recipeImage.userInteractionEnabled = true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredientsList.count
}
func addNameToDetailsViewController(nameToDetail: NSString) {
ingredientsList.append(nameToDetail as String)
if tableView == nil {
return
}
tableView!.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let ingredientName = ingredientsList[row]
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel!.text = ingredientName
return cell
}
//Picka a imagem pelo toque, acessando a PhotoLibrary
func chooseImage(recognizer: UITapGestureRecognizer) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
//Ao selecionar a imagem, coloca-a na tela tocada
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject:AnyObject]) {
let pickedImage: UIImage = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
// small picture
let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(75,75))
var sizeOfImageView:CGRect = recipeImage.frame
sizeOfImageView.size = smallPicture.size
recipeImage.frame = sizeOfImageView
recipeImage.image = smallPicture
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
func scaleImageWith(image:UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRectMake(0,0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
#IBAction func showNewIngredientScreen() {
let newIngredient = AddIngredientViewController(delegate: self)
if let navigation = navigationController {
navigation.pushViewController(newIngredient, animated: true)
}
}
#IBAction func showHowToDoScreen() {
let howToDo = HowToDoViewController(nibName: "HowToDoViewController", bundle: nil)
if let navigation = navigationController {
navigation.pushViewController(howToDo, animated: true)
}
}
#IBAction func addButton(sender: AnyObject) {
if nameTextField == nil || recipeImage == nil { return }
if recipeImage == nil { return }
let nameLabel = nameTextField.text
let imageView = recipeImage.image
if delegateDetails == nil { return }
delegateDetails?.sendDetailsToMVC(nameLabel, image: imageView!)
println("button pressed, name \(nameLabel) and image \(imageView) added.")
if let navigation = self.navigationController {
navigation.popViewControllerAnimated(true)
}
}
My question is: am I passing the information correctly? Is the correct way for storing images creating images arrays like I did? When I press the addButton, nothing happens, but it has no crashes. I'm in this issue for quite some time already and I would be very thankful if someone pointed to me what's wrong.
By the way, I'm new to Swift, so forgive me for any n00b mistakes.
Thanks!
Should be the same as in your other question. In the addButton function you are only setting the delegate if not niland not if you should. So delete if delegateDetails == nil { return } from the DetailViewControler - addButton and it should work.