Advertisement
ZTCYING

Lab9- CDpeople(image)

May 4th, 2024
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 13.00 KB | None | 0 0
  1. //
  2. //  AppDelegate.swift
  3. //  CD People
  4. //
  5. //  Created by stabirca on 21/03/2021.
  6. //
  7.  
  8. import UIKit
  9. import CoreData
  10.  
  11. @main
  12. class AppDelegate: UIResponder, UIApplicationDelegate {
  13.  
  14.  
  15.  
  16.     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  17.         // Override point for customization after application launch.
  18.         return true
  19.     }
  20.  
  21.     // MARK: UISceneSession Lifecycle
  22.  
  23.     func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
  24.         // Called when a new scene session is being created.
  25.         // Use this method to select a configuration to create the new scene with.
  26.         return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  27.     }
  28.  
  29.     func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  30.         // Called when the user discards a scene session.
  31.         // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  32.         // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  33.     }
  34.  
  35.     // MARK: - Core Data stack
  36.  
  37.     lazy var persistentContainer: NSPersistentContainer = {
  38.         /*
  39.          The persistent container for the application. This implementation
  40.          creates and returns a container, having loaded the store for the
  41.          application to it. This property is optional since there are legitimate
  42.          error conditions that could cause the creation of the store to fail.
  43.         */
  44.         let container = NSPersistentContainer(name: "CD_People")
  45.         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
  46.             if let error = error as NSError? {
  47.                 // Replace this implementation with code to handle the error appropriately.
  48.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  49.                  
  50.                 /*
  51.                  Typical reasons for an error here include:
  52.                  * The parent directory does not exist, cannot be created, or disallows writing.
  53.                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  54.                  * The device is out of space.
  55.                  * The store could not be migrated to the current model version.
  56.                  Check the error message to determine what the actual problem was.
  57.                  */
  58.                 fatalError("Unresolved error \(error), \(error.userInfo)")
  59.             }
  60.         })
  61.         return container
  62.     }()
  63.  
  64.     // MARK: - Core Data Saving support
  65.  
  66.     func saveContext () {
  67.         let context = persistentContainer.viewContext
  68.         if context.hasChanges {
  69.             do {
  70.                 try context.save()
  71.             } catch {
  72.                 // Replace this implementation with code to handle the error appropriately.
  73.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  74.                 let nserror = error as NSError
  75.                 fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
  76.             }
  77.         }
  78.     }
  79.  
  80. }
  81.  
  82. //
  83. //  SceneDelegate.swift
  84. //  CD People
  85. //
  86. //  Created by stabirca on 21/03/2021.
  87. //
  88.  
  89. import UIKit
  90.  
  91. class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  92.  
  93.     var window: UIWindow?
  94.  
  95.  
  96.     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
  97.         // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
  98.         // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
  99.         // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
  100.         guard let _ = (scene as? UIWindowScene) else { return }
  101.     }
  102.  
  103.     func sceneDidDisconnect(_ scene: UIScene) {
  104.         // Called as the scene is being released by the system.
  105.         // This occurs shortly after the scene enters the background, or when its session is discarded.
  106.         // Release any resources associated with this scene that can be re-created the next time the scene connects.
  107.         // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
  108.     }
  109.  
  110.     func sceneDidBecomeActive(_ scene: UIScene) {
  111.         // Called when the scene has moved from an inactive state to an active state.
  112.         // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
  113.     }
  114.  
  115.     func sceneWillResignActive(_ scene: UIScene) {
  116.         // Called when the scene will move from an active state to an inactive state.
  117.         // This may occur due to temporary interruptions (ex. an incoming phone call).
  118.     }
  119.  
  120.     func sceneWillEnterForeground(_ scene: UIScene) {
  121.         // Called as the scene transitions from the background to the foreground.
  122.         // Use this method to undo the changes made on entering the background.
  123.     }
  124.  
  125.     func sceneDidEnterBackground(_ scene: UIScene) {
  126.         // Called as the scene transitions from the foreground to the background.
  127.         // Use this method to save data, release shared resources, and store enough scene-specific state information
  128.         // to restore the scene back to its current state.
  129.  
  130.         // Save changes in the application's managed object context when the application transitions to the background.
  131.         (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
  132.     }
  133.  
  134.  
  135. }
  136.  
  137. //
  138. //  PeopleTableViewController.swift
  139. //  CD People
  140. //
  141. //  Created by stabirca on 21/03/2021.
  142. //
  143.  
  144. import UIKit
  145. import CoreData
  146.  
  147. class PeopleTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
  148.    
  149.     // core data objects and functions
  150.     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  151.     var pManagedObject : People! = nil
  152.     var pEntity : NSEntityDescription! = nil
  153.     var frc : NSFetchedResultsController<NSFetchRequestResult>! = nil
  154.    
  155.     func makeRequest() -> NSFetchRequest<NSFetchRequestResult>{
  156.         let request = NSFetchRequest<NSFetchRequestResult>(entityName: "People")
  157.         // define predicates and sorters
  158.         let sorter = NSSortDescriptor(key: "name", ascending: true)
  159.         request.sortDescriptors = [sorter]
  160.        
  161.         return request
  162.     }
  163.    
  164.  
  165.     override func viewDidLoad() {
  166.         super.viewDidLoad()
  167.        
  168.         // frc gets the data from People
  169.         frc = NSFetchedResultsController(fetchRequest: makeRequest(), managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
  170.        
  171.         frc.delegate = self
  172.         do{
  173.             try frc.performFetch()
  174.         }catch{
  175.             print("CD CANNOT FETCH")
  176.         }
  177.  
  178.     }
  179.    
  180.     func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  181.        
  182.         tableView.reloadData()
  183.        
  184.     }
  185.  
  186.     // MARK: - Table view data source
  187.  
  188.     override func numberOfSections(in tableView: UITableView) -> Int {
  189.         // #warning Incomplete implementation, return the number of sections
  190.         return 1
  191.     }
  192.  
  193.     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  194.         // #warning Incomplete implementation, return the number of rows
  195.         return frc.sections![section].numberOfObjects
  196.     }
  197.    
  198.  
  199.     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  200.         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
  201.  
  202.         // Configure the cell...
  203.         pManagedObject = (frc.object(at: indexPath) as! People)
  204.        
  205.         cell.textLabel?.text = pManagedObject.name
  206.         cell.detailTextLabel?.text = pManagedObject.phone
  207.  
  208.         return cell
  209.     }
  210.    
  211.  
  212.    
  213.     // Override to support conditional editing of the table view.
  214.     override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  215.         // Return false if you do not want the specified item to be editable.
  216.         return true
  217.     }
  218.    
  219.  
  220.    
  221.     // Override to support editing the table view.
  222.     override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  223.         if editingStyle == .delete {
  224.             // Delete the row from the data source
  225.             pManagedObject = frc.object(at: indexPath) as! People
  226.             context.delete(pManagedObject)
  227.            
  228.             do{
  229.                 try context.save()
  230.             }catch{
  231.                 print("CD CONTEXT CANNOT SAVE")
  232.             }
  233.            
  234.             do{
  235.                 try frc.performFetch()
  236.             }catch{
  237.                 print("CD CANNOT FETCH")
  238.             }
  239.            
  240.             tableView.reloadData()
  241.            
  242.         }
  243.     }
  244.    
  245.  
  246.     /*
  247.     // Override to support rearranging the table view.
  248.     override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
  249.  
  250.     }
  251.     */
  252.  
  253.     /*
  254.     // Override to support conditional rearranging of the table view.
  255.     override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
  256.         // Return false if you do not want the item to be re-orderable.
  257.         return true
  258.     }
  259.     */
  260.  
  261.    
  262.     // MARK: - Navigation
  263.  
  264.     // In a storyboard-based application, you will often want to do a little preparation before navigation
  265.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  266.         if segue.identifier == "cellSegue"{
  267.             // get the data from frc of indexPath
  268.             let indexPath = tableView.indexPath(for: sender as! UITableViewCell)
  269.             pManagedObject = frc.object(at: indexPath!) as! People
  270.            
  271.             // push to AddPersonController
  272.             let destination = segue.destination as! AddPersonViewController
  273.             destination.pManagedObject = self.pManagedObject
  274.         }
  275.        
  276.     }
  277.    
  278.  
  279. }
  280.  
  281. //
  282. //  AddPersonViewController.swift
  283. //  CD People
  284. //
  285. //  Created by stabirca on 21/03/2021.
  286. //
  287.  
  288. import UIKit
  289. import CoreData
  290.  
  291. class AddPersonViewController: UIViewController {
  292.     // outlets and action
  293.    
  294.     @IBOutlet weak var nameTF: UITextField!
  295.     @IBOutlet weak var phoneTF: UITextField!
  296.     @IBOutlet weak var addressTF: UITextField!
  297.     @IBOutlet weak var emailTF: UITextField!
  298.     @IBOutlet weak var imageTF: UITextField!
  299.    
  300.     @IBAction func addUpdateAction(_ sender: Any) {
  301.         if pManagedObject == nil{save()}
  302.         else {update()}
  303.        
  304.         navigationController?.popViewController(animated: true)
  305.        
  306.     }
  307.    
  308.    
  309.     // core data objects and functions
  310.     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  311.     var pManagedObject : People! = nil
  312.     var pEntity : NSEntityDescription! = nil
  313.  
  314.     override func viewDidLoad() {
  315.         super.viewDidLoad()
  316.         // setup the TF-s
  317.         if pManagedObject != nil{
  318.             nameTF.text  = pManagedObject.name
  319.             phoneTF.text = pManagedObject.phone
  320.             addressTF.text = pManagedObject.address
  321.             emailTF.text = pManagedObject.email
  322.             imageTF.text = pManagedObject.image
  323.         }
  324.     }
  325.    
  326.     // function to deal with data
  327.    
  328.     func update(){
  329.         // update the pManagedObject
  330.         pManagedObject.name = nameTF.text
  331.         pManagedObject.phone = phoneTF.text
  332.         pManagedObject.address = addressTF.text
  333.         pManagedObject.email = emailTF.text
  334.         pManagedObject.image = imageTF.text
  335.        
  336.         do{
  337.             try context.save()
  338.         }catch{
  339.             print("CD CONTEXT CANNOT SAVE")
  340.         }
  341.     }
  342.  
  343.     func save(){
  344.         // create a new managed object
  345.         pEntity = NSEntityDescription.entity(forEntityName: "People", in: context)
  346.         pManagedObject = People(entity: pEntity, insertInto: context)
  347.        
  348.         // update the pManagedObject
  349.         pManagedObject.name = nameTF.text
  350.         pManagedObject.phone = phoneTF.text
  351.         pManagedObject.address = addressTF.text
  352.         pManagedObject.email = emailTF.text
  353.         pManagedObject.image = imageTF.text
  354.        
  355.         do{
  356.             try context.save()
  357.         }catch{
  358.             print("CD CONTEXT CANNOT SAVE")
  359.         }
  360.     }
  361. }
  362.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement