XCode Swift - Deleting from core data - xcode

so far I have created an app that allows me to add a user to core data. However, I am having difficulty figuring out how to delete a user. The btnSave button achieves what it intends, however I am not having any luck attempting to fetch the user and then perform a delete. Please have a look at my included code and let me know if anyone can help. Thanks much in advance.
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet weak var txtUsername: UITextField!
#IBOutlet weak var txtPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnLoad(sender: UIButton) {
//println("Load Button\(txtUsername.text)")
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext=appDel.managedObjectContext!
var request=NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults=false
request.predicate=NSPredicate(format:"username=%#",""+txtUsername.text)
var results:NSArray=context.executeFetchRequest(request, error:nil)!
if results.count>0{
//for res in results{
// println(res)
var res=results[0] as NSManagedObject
txtUsername.text=res.valueForKey("username")as String
txtPassword.text=res.valueForKey("password") as String
//}
}else{
println("0 results or potential error")
}
}
#IBAction func btnSave(sender: UIButton) {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext=appDel.managedObjectContext!
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
newUser.setValue("\(txtUsername.text)", forKey: "username")
newUser.setValue("\(txtPassword.text)", forKey: "password")
context.save(nil)
println(newUser)
println("saved")
}
#IBAction func btnDelete(sender: UIButton) {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext=appDel.managedObjectContext!
var delUser = NSEntityDescription.delete("Users")
context.delete(nil)
}
}

An NSManagedObject is simply deleted by passing it to the NSManagedObjectContext.deleteObject(...) method. So you first need a reference to the NSManagedObject for your user, then:
context.deleteObject(user)

var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext=appDel.managedObjectContext!
var request=NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults=false
request.predicate=NSPredicate(format:"username=%#",""+txtUsername.text)
var results:NSArray=context.executeFetchRequest(request, error:nil)!
if results.count>0{
//for res in results{
// println(res)
var res=results[0] as NSManagedObject
txtUsername.text=res.valueForKey("username")as String
txtPassword.text=res.valueForKey("password") as String
context.deleteObject(res)
//}
}else{
println("0 results or potential error")
}
println("deleted")

Related

Only instance methods can be declared #IBAction | XCODE ERROR | Swift 5

Here's my code do not suggest to remove IBAction I'm a beginner making a browser. I'm also
pretty new to this program:
import Cocoa
import WebKit
class ViewController: NSViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
}
}
#IBAction func didEnterKeyTapped( sender: NSTextField){
let urlString = sender.stringValue
guard let url = URL(string: urlString) else {return}
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
#IBAction func didnavigationButtonTapped ( sender: NSSegmentedControl){
if sender.selectedSegment == 0 {
webView.goBack()
}else {
webView.Forward()
}
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
let currentUrl = webView.url?.absoluteString ?? ""
guard let windowController = view.window?.windowController as? WindowController else {return}
let textField = windowController.urlTextField
textField?.stringValue = currentUrl
}
}
}
You declared the #IBActions outside of the ViewController class. An IBAction must be a member of a class. Move the IBActions inside the class to fix the compiler error.
Another problem in your code is you declared the didNavigationButtonTapped IBAction inside the didEnterKeyTapped IBAction. The two IBActions should be separate functions, such as the following:
#IBAction func didEnterKeyTapped( sender: NSTextField){
let urlString = sender.stringValue
guard let url = URL(string: urlString) else {return}
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
#IBAction func didnavigationButtonTapped ( sender: NSSegmentedControl) {
if sender.selectedSegment == 0 {
webView.goBack()
}else {
webView.Forward()
}
}

swift 4- Save the last data of a text field in a label so that they are displayed when the app is restarted

I have a problem, I want to create a small app in which data in a formula can be charged.
Currently the data from three ViewControllers and one PickerViewController will be given back to the first ViewController.
That works very well too.
Now I want that the data at the start not on "nil" set but have a certain value.
Thereafter, the data entered last should reappear when the app is restarted.
I would like to apologize for my english, it is not my preferred language ...
Here is a part of my code how I wrote it
Main ViewController:
import UIKit
class RecivingViewController: UIViewController, SendDataBack, SendDataBack2, SendDataBack3, SendDataBack4 {
#IBOutlet weak var recivingData: UILabel!
#IBOutlet weak var recivingData2: UILabel!
#IBOutlet weak var recivingData3: UILabel!
#IBOutlet weak var recivingData4: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func userData(data: String) {
recivingData.text = data
}
func userData2(data: String) {
recivingData2.text = data
}
func userData3(data: String) {
recivingData3.text = data
}
func PickerData(data: String){
recivingData4.text = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "view1" {
let SendingVC: SendingViewController = segue.destination as! SendingViewController
SendingVC.delegate = self
}
if segue.identifier == "view2" {
let SendingVC2: Sending2ViewController = segue.destination as! Sending2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "view3" {
let SendingVC3: Sending3ViewController = segue.destination as! Sending3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "picker" {
let SendingVC4: PickerViewController = segue.destination as! PickerViewController
SendingVC4.delegate = self
}
}
}
one of the other ViewControllers:
import UIKit
protocol SendDataBack {
func userData(data: String)
}
class SendingViewController: UIViewController {
#IBOutlet weak var DataTxt: UITextField!
var delegate: SendDataBack? = nil
#IBAction func done(_ sender: Any) {
if delegate != nil {
if DataTxt.text != nil {
let data = DataTxt.text
delegate?.userData(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
In order to see data after app is restarted you should use user defaults.
For saving data
UserDefaults.standard.set(newValue, forKey: "data")
For loading data in your view controller, if it's first load, when data is nil
UserDefaults.standard.string(forKey: "data")

Pass data via segue between 2 view controllers and update labels

I am trying to pass var projectNumber from ViewController to Project1ViewController via segue and save it as var projectNum. Then use projectNum to update the labels in Project1ViewController. The segue and action/outlets are all set up. The app runs fluently (no errors), however, projectNum in Project1ViewController is not getting the projectNumber value and making it projectNum.
How do I pass the projectNumber value from ViewController to Project1ViewController and save it in projectNum? I've seen tutorials that describe similar actions being performed via delegates, but I'm unsure if delegates are applicable to my question. Any feedback helps.
ViewController
import UIKit
class ViewController: UIViewController{
var projectNumber:String = ""
#IBOutlet var projectButton1 : UIButton!
#IBOutlet var projectButton2 : UIButton!
#IBOutlet var projectButton3 : UIButton!
#IBOutlet var projectButton4 : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func updateLabels(sender: UIButton!) {
projectNumber = String(sender.tag)
println(projectNumber)
sender.setTitle(String(projectNumber), forState: UIControlState.Normal)
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
//if user presses Project 3921 button
if segue.identifier == "Project3921Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//if user presses Project 3922 button
else if segue.identifier == "Project3922Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//if user presses Project 3923 button
else if segue.identifier == "Project3923Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
//otherwise user presses Project 3924 button
else if segue.identifier == "Project3924Segue"
{
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = projectNumber
}
}
}
}
}
Project1ViewController
import UIKit
class Project1ViewController: UIViewController {
var projectNum:String!
#IBOutlet var projectNumLabel: UILabel!
#IBOutlet var projectNumTitle: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
projectNumLabel.text = projectNum
projectNumTitle.title = projectNum
println(projectNum)
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks!
You are defining prepareForSegueinside the button action function. It is a ViewController function to be overridden.
Your solution can be way more simpler:
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if var destinationVC = segue.destinationViewController as? Project1ViewController{
destinationVC.projectNum = segue.identifier
}
}
}
Note you do not need the button outlets, since you just configure them in the storyboard with the proper segue identifier. Unless you need some other custom action to be triggered by the buttons.
And:
class Project1ViewController: UIViewController {
var projectNum:String!
#IBOutlet var projectNumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
projectNumLabel.text = projectNum
self.title = projectNum
println(projectNum)
}
}
Note I just set the title property of Project1ViewController in order to present the projectNum as the title in the navigation controller. I assume your controllers are embedded in a navigation controller and the ViewController's buttons has show segues to Project1ViewController.

How to use public NSURL Variable

I'm new to Swift and Xcode overall,
I want to create a new public NSURL variable which I want to use later in my code to give it value and use that value later from it. like below :
class AddUrlViewController: NSViewController {
#IBOutlet weak var txtPath: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnFileDialog(sender: NSButton) {
let myFiledialog:NSOpenPanel = NSOpenPanel()
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
var returnCode:NSInteger = myFiledialog.runModal()
if (returnCode == NSOKButton) {
/////////// Use it here
var directoryUrl = myFiledialog.URL?.absoluteURL
}
}
#IBAction func btnStart(sender: NSButton) {
//////////// Use it here
}
}
How should I achieve this the best way ?
Simply define the variable as a property outside of the function scope -
class AddUrlViewController: NSViewController {
#IBOutlet weak var txtPath: NSTextField!
var directoryUrl:NSURL?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnFileDialog(sender: NSButton) {
let myFiledialog:NSOpenPanel = NSOpenPanel()
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
var returnCode:NSInteger = myFiledialog.runModal()
if (returnCode == NSOKButton) {
/////////// Use it here
self.directoryUrl = myFiledialog.URL?.absoluteURL
}
}
#IBAction func btnStart(sender: NSButton) {
if (self.directoryUrl != nil) {
//////////// Use it here
}
}
}

Updates Labels in Swift when using popoverController

I have a question about swift,
I made a popover controller in a UIViewController,which display a list of books
and when the user click on one of the books, the label on the viewController should be updated with the name of the selected book.
But in my case when I select a name of a book, the label does not update
here is the code :
// View Controller
import UIKit
class ViewController: UIViewController,UIPopoverControllerDelegate {
var popoverController : UIPopoverController? = nil
#IBOutlet var bookName : UILabel
var BookNameString : String?{
didSet{
configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.BookNameString {
if let label = bookName {
label.text = detail
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Click(sender : UIButton) {
var tableView:TableViewController = TableViewController(style: UITableViewStyle.Plain)
var popoverContent:UINavigationController = UINavigationController(rootViewController: tableView)
self.popoverController = UIPopoverController(contentViewController: popoverContent)
self.popoverController!.delegate = self
self.popoverController!.presentPopoverFromRect(sender.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and here is the code of the TableViewController when a row is selected:
// TableViewController
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var details = storyboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
var keyString = bookSectionKeys[indexPath.section]
var bookValues = book.booksLetters[keyString]!
var selectedBookString = bookValues[indexPath.row]
var selectedBookValues = book.bookDictionary[selectedBookString]!
details.BookNameString = selectedBookString
}
I was able to solve this problem a few weeks ago and I want to share the solution with you :)
I solve it using protocols.
OK Here what I did in details:
First I created a protocol in the view that I want it to display inside the popover and I named the protocol "DismissPopoverDelegate"
protocol DismissPopoverDelegate{
func didSelectBook(SelectedBook:String)
}
Then I declared a variable of type DismissPopoverDelegate and name it "delegate"
var delegate: DismissPopoverDelegate?
Then in the didSelectRowAtIndexMethod:
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var keyString = bookSectionKeys[indexPath.section]
var bookValues = book.booksLetters[keyString]!
var selectedBookString = bookValues[indexPath.row]
delegate?.didSelectBook(selectedBookString)
}
After that inside the View that contains the popover (View Controller), I set the delegate of the view:
class ViewController: UIViewController, DismissPopOverDelegate, UIPopoverControllerDelegate{
Then to make the view confirm to the protocol DismissPopOverDelegate, I implement the method "didSelectBook" Inside the view:
func didSelectBook(SelectedBook:String){
popoverController!.dismissPopoverAnimated(true) // This is Optional
bookName.text = SelectedBook // Make the label text equal to the selected book From the table
}
Finally, I set the delegate to the tableView to View Controller
tableView.delegate = self
That's it :)
Here is the full code of the viewController that contains the popover
import UIKit
class ViewController: UIViewController, DismissPopOverDelegate, UIPopoverControllerDelegate{
#IBOutlet var booksbarButton : UIBarButtonItem
#IBOutlet var bookName : UILabel
var popoverController : UIPopoverController? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func showTableView(sender : UIBarButtonItem) {
var tableView:TableViewController = TableViewController(style: UITableViewStyle.Plain)
tableView.delegate = self
var popoverContent:UINavigationController = UINavigationController(rootViewController: tableView)
self.popoverController = UIPopoverController(contentViewController: popoverContent)
popoverController!.delegate = self
self.popoverController!.presentPopoverFromBarButtonItem(booksbarButton, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
func didSelectBook(SelectedBook:String){
popoverController!.dismissPopoverAnimated(true)
bookName.text = SelectedBook
}
}

Resources