Wednesday, 1 August 2018

Core Data - List the values, Add the Core Data

ListViewController.swift
import UIKit
import CoreData

class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
   
    var arr_Emp:[NSManagedObject] = retriveItem_CoreData(e_name: "", e_id: 0)
    @IBOutlet var tbl_view: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        tbl_view?.reloadData()
        // Do any additional setup after loading the view.
    }
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr_Emp.count
    }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tbl_view?.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as UITableViewCell!
        let employee = arr_Emp[indexPath.row]
        cell.textLabel?.text = employee.value(forKey: "e_name") as? String
        cell.textLabel?.textAlignment = .center
        return cell
    }
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let add_vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "AddViewController") as? AddViewController
        add_vc?.page_id = 1234
        let employee = arr_Emp[indexPath.row]
        add_vc?.emp_Details = employee
        self.navigationController?.pushViewController(add_vc!, animated: true)
    }
}

AddViewController.swift
import UIKit
import CoreData

class AddViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet var txtfld_ename: UITextField!
    @IBOutlet var txtfld_eid: UITextField!
    @IBOutlet var txtfld_edest: UITextField!
    @IBOutlet var txtfld_eaddr: UITextField!
    @IBOutlet var btn_Map:UIButton!
    @IBOutlet var img_photo: UIImageView!
    @IBOutlet var lbl_NoPhoto: UILabel!
    
    @IBOutlet var btn_Save:UIButton!
    @IBOutlet var btn_Cancel:UIButton!
      
    var page_id:Int = 0
    var emp_Details:NSManagedObject? = NSManagedObject()
    var imagePicker = UIImagePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Add Data"
        imagePicker.delegate = self
        
        btn_Map.alpha = 0.0
        
        if page_id == 1234 {
            self.title = "View Data"
            
            txtfld_ename.isUserInteractionEnabled = false
            txtfld_eid.isUserInteractionEnabled = false
            txtfld_edest.isUserInteractionEnabled = false
            txtfld_eaddr.isUserInteractionEnabled = false
            
            txtfld_ename?.text = emp_Details?.value(forKey: "e_name") as? String
            txtfld_eid?.text = "\(emp_Details?.value(forKey: "e_id") as? Int)"
            txtfld_edest?.text = emp_Details?.value(forKey: "e_destination") as? String
            txtfld_eaddr?.text = emp_Details?.value(forKey: "e_address") as? String
            let str_photopath = emp_Details?.value(forKey: "e_photo_path") as? String
            if str_photopath != nil {
                img_photo.image =  GetImage(str_name: str_photopath!)
            }
            
            btn_Map.alpha = 1.0
            lbl_NoPhoto.alpha = 0.0
            
            btn_Save.alpha = 0.0
            btn_Cancel.alpha = 0.0
        }
        
        // Do any additional setup after loading the view.
    }

    @IBAction func browse_Action(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
            imagePicker.sourceType = .savedPhotosAlbum;
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    @IBAction func view_Action(_ sender: Any) {
        
    }
    
    @IBAction func openMap_Action(_ sender: Any) {
        let str_addr = txtfld_eaddr.text
        guard let url = URL(string: "https://www.google.com/maps/\(str_addr)") else {
            return
        }
        
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
        else {
            UIApplication.shared.openURL(url)
        }
    }
    
    
    @IBAction func save_Action(_ sender: Any) {
        let str_name = txtfld_ename.text
        let str_id = txtfld_eid.text
        let str_dest = txtfld_edest.text
        let str_addr = txtfld_eaddr.text
        
        let e_id_val:Int = Int(str_id!)!
        
        if img_photo.image != nil && (str_name?.characters.count)! > 0 && (str_id?.characters.count)! > 0 && (str_dest?.characters.count)! > 0 && (str_addr?.characters.count)! > 0 {
            let str_photoname = custom_name_generate()
            SaveImage(str_name: str_photoname, img_Save: img_photo.image!)
            let stats:Bool = saveItem_CoreData(e_name: str_name!, e_id: e_id_val, e_destination: str_dest!, e_address: str_addr!, e_photo_path: str_photoname)
            if stats == true {
                let actionSheetController: UIAlertController = UIAlertController(title: "Message!!!", message: "Your Item is Added to core data.", preferredStyle: .actionSheet)
                let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
                    self.navigationController?.popViewController(animated: true)
                }
                actionSheetController.addAction(okAction)
                self.present(actionSheetController, animated: true, completion: nil)
            }
        }
        else {
            let actionSheetController: UIAlertController = UIAlertController(title: "Message!!!", message: "Please fill all details", preferredStyle: .actionSheet)
            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
            }
            actionSheetController.addAction(okAction)
            self.present(actionSheetController, animated: true, completion: nil)
        }
    }
    
    
    @IBAction func cancel_Action(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    //MARK: Text Field Delegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    //MARK: Image Picker Delegate
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //save image
            //display image
            img_photo.image = image
            lbl_NoPhoto.alpha = 0.0
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
}

CommonClass.Swift
import Foundation
import UIKit
import CoreData

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let checkValidation = FileManager.default
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let managedContext = appDelegate?.persistentContainer.viewContext

func saveItem_CoreData(e_name: String, e_id: Int, e_destination: String, e_address: String, e_photo_path: String) -> Bool {
    var stats = true
    let entity = NSEntityDescription.entity(forEntityName: "Employee", in: managedContext!)!
    let employee = NSManagedObject(entity: entity, insertInto: managedContext!)
    employee.setValue(e_name, forKeyPath: "e_name")
    employee.setValue(e_id, forKeyPath: "e_id")
    employee.setValue(e_destination, forKeyPath: "e_destination")
    employee.setValue(e_address, forKeyPath: "e_address")
    employee.setValue(e_photo_path, forKeyPath: "e_photo_path")
    do {
        try managedContext!.save()
    }
    catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
        stats = false
    }
    return stats
}

func retriveItem_CoreData(e_name: String, e_id: Int) -> [NSManagedObject] {
    var arr_Emp = [NSManagedObject]()
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Employee")
    //fetchRequest.predicate = NSPredicate(format: "e_name == %@", e_name)
    do {
        arr_Emp = try managedContext!.fetch(fetchRequest)
        print(arr_Emp.count)
    }
    catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
    return arr_Emp
}

func custom_name_generate() -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "ddMMyyyy_HHmmss"
    let date_val = formatter.string(from: Date())
    let custom_name = "image_\(date_val).png"
    return custom_name
}

func SaveImage(str_name:String, img_Save:UIImage) {
    let getImagePath = paths.appending(str_name)
    if (checkValidation.fileExists(atPath: getImagePath))
    {
        print("Already Image saved samename")
    }
    else
    {
        let imageData =  UIImageJPEGRepresentation(img_Save, 1.0)
        try! imageData?.write(to: URL.init(fileURLWithPath: getImagePath), options: .atomicWrite)
    }
}

func GetImage(str_name:String) -> UIImage {
    var imgRetrive: UIImage = UIImage()
    let getImagePath = paths.appending(str_name)
    if (checkValidation.fileExists(atPath: getImagePath))
    {
        imgRetrive = UIImage(contentsOfFile: getImagePath)!
        //try! checkValidation.removeItem(atPath: getImagePath)
    }
    return imgRetrive
}