iOS - How to insert a new To-Do item in a single view controller? - swift3

I want to add a new To Do item when i press the add button,but i don't want to switch to another page.
press the add button to add a new row in the table view,input something and press the done button,it will save.
somebody suggests me to save the cells data to Model,but i don't know how to write this.
Who can help me?
import UIKit
import CoreData
class ToDoViewController: UIViewController {
var items: [NSManagedObject] = []
#IBOutlet weak var tableView: UITableView!
#IBAction func addItem(_ sender: UIBarButtonItem) {
//***How to write this code***
}
#IBAction func done(_ sender: UIBarButtonItem) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "ToDo", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
//***let list = the current textView's text
//how to get the textView's text and assign it to a value.***
item.setValue(list, forKeyPath: "summary")
do {
try managedContext.save()
items.append(item)
} catch let error as NSError {
print("Could not save.\(error),\(error.userInfo)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self,forCellReuseIdentifier: "Cell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "ToDo")
do {
items = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch.\(error),\(error.userInfo)")
}
}
}
extension ToDoViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height))
cell.addSubview(textView)
textView.text = item.value(forKey: "summary") as? String
return cell
}
}

Ok so If my understanding is right you need a new row to be added if they create a new entry into your Core Data. So in your viewWillAppear you're doing a fetch. What I think you need is a:
var fetchResultController : NSFetchedResultsController<YourType>!
Then using this fetch controller you want to do the following when fetching:
private func GetToDoEntries(){
if let appDele = UIApplication.shared.deletgate as? AppDelegate{
let givenContext = appDele.persistantContainer.viewContex
let entryFetchRequest : NSFetchRequest<YourType> = YourType.fetchRequest()
let sortDescriptors = NSSortDescriptor(key: "yourEntrySortKey" , ascending: true)
entryFetchRequest.sortDescriptors = [sortDescriptors]
fetchResultController = NSFetchedResultsController(fetchRequest: entryFetchRequest, managedObjectContext: givenContext, sectionNameKeyPath: nil, cacheName: nil)
fetchResultController.delegate = self
do{
//Gets fetched data based on our criteria
try fetchResultController.performFetch()
if let fetchedEntries = fetchResultController.fetchedObjects{
items = fetchedEntries as? WhateverToCastTo
}
}catch{
print("Error when trying to find entries")
}
}
}
First I'm sorry but I've just written this here is stackOverflow. So what you're doing is using a fetch result controller instead of a traditional search. You are required to have the sort descriptor as well and you can try to get the results and cast them to your items or as a NSManagedObject.
Now we're not done though. Your script needs to inherit from some behaviour. At the top of your class
class ToDoViewController : UIViewController, NSFetchedResultsControllerDelegate
You need the delegate as you can see in the first block of code because we're assigning it. Now we're almost there. You just need some methods to update the table for you and these come with the delegate we just inherited from.
//Allows the fetch controller to update
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
//Allows new additions to be added to the table
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type{
case .insert:
if let _newIndexPath = newIndexPath{
tableView.insertRows(at: [_newIndexPath], with: .fade)
}
case .update:
if let index = indexPath{
tableView.reloadRows(at: [index], with: .fade)
}
default:
budgetEntryTable.reloadData()
}
if let fetchedObjects = controller.fetchedObjects{
items = fetchedObjects as! [NSManagedObject (Or your cast type)]
budgetEntryTable.reloadData()
}
}
//Ends the table adding
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
So there are 3 methods here. The first and second are very self explanatory. They begin and end the updates on your tableView. I'd also recommend that you change the name of your tableView to something other than "tableView" just for clarity.
The method in the middle uses a switch. My example is missing the "Move" and "Delete" options as I didn't required them in my project but you can add them to the switch statement.
The insert is checking the newIndexPath to see if there is one. If so then we add an array of the amount of rows required at the newIndexPath.
The update just checks the current index paths and then reloads the data on them incase you updated your data model.
I hope this is what you were looking for. Good luck! I'll try and help more if you need it but that should get you started.

Related

How to present a Tabbar correctly? Unbalanced calls to begin/end appearance transitions for tabbarcontroltest.ViewController:

I have a problem showing a tabbarVC.
Here is the codes:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let tabBarVC = UITabBarController()
guard let vc1 = storyboard?.instantiateViewController(identifier: "FirstController") as? FirstController else {
print("failed to get vc1 from Storyboard")
return
}
guard let vc2 = storyboard?.instantiateViewController(identifier: "SecondController") as? SecondController else {
print("failed to get vc2 from Storyboard")
return
}
guard let vc3 = storyboard?.instantiateViewController(identifier: "ThirdController") as? ThirdController else {
print("failed to get vc3 from Storyboard")
return
}
let vc4 = UINavigationController(rootViewController: vc1)
let vc5 = UINavigationController(rootViewController: vc2)
let vc6 = UINavigationController(rootViewController: vc3)
vc4.title = "XXX"
vc5.title = "YYY"
vc6.title = "ZZZ"
tabBarVC.setViewControllers([vc4,vc5,vc6], animated: false)
tabBarVC.modalPresentationStyle = .fullScreen
self.present(tabBarVC, animated: true)
}
}
The tabbar has shown correctly, but I got a warning of "Unbalanced calls to begin/end appearance transitions for <tabbarcontroltest.ViewController:" which I don't understand.
Also I have tried to change
tabBarVC.modalPresentationStyle = .fullScreen
to
tabBarVC.modalPresentationStyle = .overFullScreen
And, then I don't have this warning, but instead, when I try to close the app by home button,
I got another warning as
tabbarcontroltest[Presentation] Attempt to present on <tabbarcontroltest.ViewController> (from <tabbarcontroltest.ViewController) which is already presenting .
I guess there is something wrong with the presentation style? Or is there something else wrong?
Thanks
found the solution by myself. the correct way is as follows:
tabBarVC.modalPresentationStyle = .fullScreen
tabBarVC.view.frame = self.view.bounds
addChild(tabBarVC)
view.addSubview(tabBarVC.view)
tabBarVC.willMove(toParent: self)

Getting nil response while passing string to another view controller - Swift3

In FirstViewController i'm fetching the response from JSON and want to pass that fetched response to another view controller.Below is the code which i have used so far for parsing and passing the response.
FirstViewController
var fn:String! //globally declared variable
code i have tried for parsing in FirstViewController
do {
let detailsDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary<String, AnyObject> as NSDictionary
print(detailsDictionary)
let details = detailsDictionary["Data"] as! [[String:AnyObject]]
print(details)
for dtl in details
{
self.fn = dtl["Father_Name"] as? String ?? "NA"
print(self.fn) //here i'm getting the exact value from JSON
}
}
}
SecondViewController
In SecondViewController there is a Label called profile_name and want to set that parsed string(fn) as Label's text. for that i declared another variable as global.
var pname:String!
below is the code i have used to fetch the value from FirstViewController.
viewDidLoad()
{
let othervc = FirstViewController()
self.pname = othervc.fn
self.profile_name.text = self.pname
}
Problem : I tried my best efforts to get the desired output but i'm getting nil response.
Please Help.
In Second ViewController
let strName:String!
In First ViewController
let strOne = "This is for testing"
let objstory = self.storyboard?.instantiateViewController(withIdentifier: "yout Secoond ViewController Storybord ID") as! YourSecondViewControllerName
objstory.strNam = strOne
self.navigationController?.pushViewController(objstory, animated: true)
Your updated code just won't work.
let othervc = FirstViewController()
creates a new instance of FirstViewController (not the one that got the JSON).
You should be handling it something like this:
In FirstViewController
let fn = dtl["Father_Name"] as? String ?? "NA"
let svc = SecondViewController() // Or maybe instantiate from Storyboard, or maybe you already have a reference to it
svc.pname = fn
present(svc, animated: true, completion: nil)
Then in SecondViewController
override func viewDidLoad() {
super.viewDidLoad()
profile_name.text = pname
}
I'd suggest you take some time out and re-read Apple's View Controller programming guide.
Original Answer
The problem you have here…
vcvalue.profile_name.text = fn
is that profile_name is nil as the view for the view controller hasn't been loaded at this point.
You should handle this by creating a property in LeftSideMenuViewController
var name: String?
Then set
vcvalue.name = fn
And then in LeftSideMenuViewController
override func viewDidLoad() {
super.viewDidLoad()
profile_name.text = name
}
Also, some basic tips…
Don't force unwrap (!) apart from IBOutlets. You may have to write a bit more code, but you will reduce crashes.
Make #IBOutlets private - this will prevent you accidentally assigning to them as you are now
If you're overriding any viewWill/DidDis/Appear methods, you must call super at some point.
You need to re-read the section on switch/case
So this…
let a = indexPath.row
switch(a)
{
case 0 :
if(a == 0)
{
return 45
}
break
etc
could just be…
switch indexPath.row {
case 0...4:
return 45
case 5:
return 50
default:
break
}

TableView crashes under uncaught exception 'NSUnknownKeyException', this class is not key value coding-compliant for the key x.'

I can't seem to make this tableView with custom cells work. I get a runtime error
Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[ setValue:forUndefinedKey:]: this class is not key
value coding-compliant for the key causeCampaignDescription.'
The weird thing is that that property is not called like that anymore. This is the cell file MainViewControllerTableViewCell
//
// MainViewControllerTableViewCell.swift
//
//
// Created by on 9/13/17.
// Copyright © 201. All rights reserved.
//
import UIKit
class MainViewControllerTableViewCell: UITableViewCell {
#IBOutlet weak var causeCampaignImageView: UIImageView!
#IBOutlet weak var causeDescription: UILabel!
#IBOutlet weak var daysToFinishLabel: UILabel!
#IBOutlet weak var raisedOverTotalLabel: UILabel!
#IBOutlet weak var percentageCompletedLabel: UILabel!
#IBOutlet weak var goalProgresView: UIProgressView!
//card used on
#IBInspectable var cornerradius : CGFloat = 2
#IBInspectable var shadowOffSetWidth : CGFloat = 0
#IBInspectable var shadowOffSetHeight : CGFloat = 5
#IBInspectable var shadowColor : UIColor = UIColor.black
#IBInspectable var shadowOpacity : CGFloat = 0.5
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
}
override func layoutSubviews() {
layer.cornerRadius = cornerradius
layer.shadowColor = shadowColor.cgColor
layer.shadowOffset = CGSize(width: shadowOffSetWidth, height: shadowOffSetHeight)
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerradius)
layer.shadowPath = shadowPath.cgPath
layer.shadowOpacity = Float(shadowOpacity)
}
}
and this is the view controller that holds the table view MainViewController:
//
// ViewController.swift
//
//
// Created by on 1/28/17.
// Copyright © 2017. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Firebase
class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var campaignRowsData = [CauseCampaign]()
var serverFetchCampaignsUrl = Config.Global._serverUrl
#IBOutlet weak var campaignTableView: UITableView!
//show navigation controller bar
var facebookID = "", twitterID = "",firebaseID = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//hide bar from navigation controller
setToolbar()
campaignTableView.delegate=self
campaignTableView.dataSource=self
campaignTableView.separatorColor = UIColor(white: 0.95, alpha: 1)
recoverUserDefaults()
getCampaignList()
//print(facebookID, twitterID, firebaseID)
}
func setToolbar(){
//hide bar from navigation controller
self.navigationController?.isNavigationBarHidden = false
self.navigationItem.setHidesBackButton(true, animated: false)
self.navigationController?.navigationBar.barTintColor = UIColor.purple
}
func getCampaignList(){
Alamofire.request(serverFetchCampaignsUrl+"/campaigns/get/all/user/\(twitterID)/firebase/\(firebaseID)/cat/0", method: .get).validate().responseJSON { response in
switch response.result {
case .success(let data):
let campaignCausesJSON = JSON(campaignCausesData: data)
self.parseCampaignCausesListResponse(campaignCausesJSON)
//alternative thread operation
DispatchQueue.main.async {
self.campaignTableView.reloadData()
}
case .failure(let error):
print(error)
}
}
}
func parseCampaignCausesListResponse(_ campaignCausesJSON:JSON){
if let activeCampaignCount = campaignCausesJSON["active_campaigns_count"].string {
//Now you got your value
print("TOTAL_ACTIVE_CAMPAIGNS",activeCampaignCount)
CampaignsGlobalDataManagerUtil.campaignTotalCount = Int(activeCampaignCount)!
}
if let contributorUserId = campaignCausesJSON["contributor_user_id"].string {
//Now you got your value
print("CONTRIBUTOR_USER_ID",contributorUserId)
CurrentUserUtil.contributorUserId = contributorUserId
}
if let userTwitterFollowersQty = campaignCausesJSON["user_twitter_followers_qty"].int {
//Now you got your value
print("USER_TWITTER_FOLLOWERS_QTY",userTwitterFollowersQty)
CurrentUserUtil.twitterFollowersCount = Int(userTwitterFollowersQty)
}
//Parsing campaigns object array
campaignCausesJSON["camp_array"].arrayValue.map({
let campaignCause:JSON = $0
parseCampaign(campaignCause)
})
}
//TODO:CHANGE TO DATATAPE OBJECT
func parseCampaign(_ causeCampaign:JSON){
let causeCampaignObject: CauseCampaign = CauseCampaign();
causeCampaignObject.description = causeCampaign["cause_description"].stringValue
causeCampaignObject.id = causeCampaign["campaign_id"].stringValue
if let contributorsQty = causeCampaign["contributors_qty"].int{
causeCampaignObject.contributorsQty = contributorsQty
}
causeCampaignObject.currencySymbol = causeCampaign["currency_symbol"].stringValue
if let currentContributions = causeCampaign["current_contributions"].float{
causeCampaignObject.currentContributions = currentContributions
}
if let goal = causeCampaign["goal"].float {
causeCampaignObject.goal = goal
}
if let goalPercentageAchieved = causeCampaign["goal_percentage_achieved"].float{
causeCampaignObject.goalPercentageAchieved = causeCampaign["goal_percentage_achieved"].float!
}
causeCampaignObject.hashtag = causeCampaign["hashtag"].stringValue
causeCampaignObject.name = causeCampaign["name"].stringValue
if let remainingAmmountToGoal = causeCampaign["remaining_ammount_to_goal"].float{
causeCampaignObject.remainingAmmountToGoal = remainingAmmountToGoal
}
if let picUrl = causeCampaign["pic_url"].stringValue as? String {
causeCampaignObject.picUrl = picUrl
}
if let campaignStartingDate = causeCampaign["created_at"].string{
causeCampaignObject.campaignStartingDate = campaignStartingDate
}
if let campaignEndingDate = causeCampaign["campaign_ending_date"].string{
causeCampaignObject.campaignEndingDate = campaignEndingDate
}
var foundationsArray = [Foundation]()
causeCampaign["foundations"].arrayValue.map({
let id = $0["foundation_id"].stringValue
let twitterUsername = $0["twitter_username"].stringValue
let picPath = $0["pic_path"].stringValue
let name = $0["name"].stringValue
let foundation:Foundation = Foundation(id,twitterAccount: twitterUsername,picPath: picPath,name: name)
foundationsArray.append(foundation)
})
causeCampaignObject.foundations = foundationsArray
campaignRowsData.append(causeCampaignObject)
// foundations = "<null>";
//innecesario
// SACAR DE LA REQUEST INICIAL???
// "went_inactive_date" = "<null>";
// "tweet_id" = 900936910494810112;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return campaignRowsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = campaignTableView.dequeueReusableCell(withIdentifier: "campaignCell", for: indexPath) as! MainViewControllerTableViewCell
//setting card attributes
print("ROW",campaignRowsData[indexPath.row].description)
let campaignCause:CauseCampaign = campaignRowsData[indexPath.row]
if let desc = campaignCause.description as? String{
cell.causeDescription.text = desc
} else {
print("NULL")
}
return cell
}
func recoverUserDefaults(){
if let fbID = UserDefaults.standard.object(forKey: Config.Global._facebookIdUserDefaults) as? String {
facebookID = fbID
}else{
print("FACEBOOK ID IS NULL")
}
if let twtID = UserDefaults.standard.object(forKey: Config.Global._twitterIdUserDefaults) as? String{
twitterID = twtID
}else{
print("TWITTER ID IS NULL")
}
if let firID = UserDefaults.standard.object(forKey: Config.Global._firebaseIdUserDefaults) as? String{
firebaseID = firID
}else{
print("TWITTER ID IS NULL")
}
return
}
}
The app crashes if the line reloadData is uncommented (I don't even know when and If I should use this)
If I set a label you can't see anything on screen, I see blank cards, but again, as soon as I uncomment reloadData it crashes
There's no causeCampaignDescription, now it's called causeDescription so I don't know why the error keeps mentioning that field
The data desc is ok since I printed it and it has the right content so it's not that
What could be the problem?
Searching the project for causeCampaignDescription will often turn up the offending xib and/or storyboard containing the outdated key path. However, it's been my experience that Xcode is not always 100% reliable about finding things in xibs and storyboards, so if Xcode's search feature won't find it, this command in the Terminal will turn it up straightaway:
find /path/to/your/project/directory -name .git -prune -or -type f -exec grep causeCampaignDescription {} \; -print
Once you find the offending item in the xib or storyboard, change it to the correct string and you should solve your problem.

Issue with prepare for Segue and AccessoryButtonTappedForRowWith

After clicking on a accessoryButton in TableView, it will redirect me first to PrepareforSegue function and then to accessoryButtonTappedForRowWith Function which creating error in my code.
Please have a look into my code:
var indexPathAccessory: Int?
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
indexPathAccessory = indexPath.row
}
indexPathAccessory contains the value of row where Accessorybutton was clicked.
The second function is:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Add" {
let nc = segue.destination as! UINavigatorController
controller = nc.topViewController as! AVC
//Comment 1
controller.name = span[indexPathAccessory]
//Comment 2
controller.delegate = self
}
}
I am getting error cause after clicking on accessorybutton, it is redirecting me to prepareforSegue function first and then to accessoryButtonTappedForRowWith and due to value of indexPathAccessory which still nil, I am getting this error
Will it be possible to jump first on accessoryButtonTappedForRowWith to get the value of indexPathAccessory and then to prepareForSegue?
if yes, problem will be solved.
I tried to add one test to return if indexPathAccessory is nil.
application run without error but not in a proper way:
I can see that controller.name is equal to "test", but when I am on AVC View controller, name became nil
Any advise?
One of the solution can be - remove the segue from the storyboard which causes the control going out of your hand and write the performSegue inside your accessoryButtonTappedForRowWith method.
Finally it worked by deleting the accessoryButtonTappedForRowWith function, and adding the following code to prepareforSegue functions:
if let indexPath = tableView.indexPath(for: sender as! UITableViewCell) {
controller.beamName = "Test"
indexSpanAccessory = indexPath.row
}

Swift 3 Create Reminder EKEventStore

I would like to save reminders to the default reminders location. But when I press my button I get a fatal error: unexpectedly found nil while unwrapping an Optional value... I am pretty new to this and most examples I locate are overly complicated or not in Swift 3.
class ViewController: UIViewController {
var eventStore: EKEventStore?
#IBOutlet weak var reminderText: UITextField!
#IBAction func setReminder(_ sender: Any) {
let reminder = EKReminder(eventStore: self.eventStore!)
reminder.title = "Go to the store and buy milk"
reminder.calendar = (eventStore?.defaultCalendarForNewReminders())!
do {
try eventStore?.save(reminder,
commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
}
}
}
As its a simple piece of code I thought I would post my answer after I figured it out for any future swifters. I always like simple examples.
import UIKit
import EventKit
class ViewController: UIViewController {
var eventStore = EKEventStore()
var calendars:Array<EKCalendar> = []
// Not used at this time
#IBOutlet weak var reminderText: UITextField!
#IBAction func setReminder(_ sender: Any) {
let reminder = EKReminder(eventStore: self.eventStore)
reminder.title = "Go to the store and buy milk"
reminder.calendar = eventStore.defaultCalendarForNewReminders()
do {
try eventStore.save(reminder,
commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// get permission
eventStore.requestAccess(to: EKEntityType.reminder, completion:
{(granted, error) in
if !granted {
print("Access to store not granted")
}
})
// you need calender's permission for the reminders as they live there
calendars = eventStore.calendars(for: EKEntityType.reminder)
for calendar in calendars as [EKCalendar] {
print("Calendar = \(calendar.title)")
}
}
override func viewWillAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
With the #adamprocter sample, we also need to add "NSRemindersUsageDescription" key with your message in info.plist file. I tried adding this as a comment but I am not eligible.