How to used Core data In Swift 4
Step 1:- Create new Project Step 2:- Set Project Name, bundle identifier, and Select Core data.
Step 3:- Create New File see Below.
import UIKit
import CoreData
class CoreData: NSObject {
static let sharedInstance = CoreData()
func manageObjectContext() -> NSManagedObjectContext? {
let urlModel: URL? = Bundle.main.url(forResource: "DemoChat", withExtension: "momd")
let objectModel: NSManagedObjectModel? = NSManagedObjectModel(contentsOf: urlModel!)
let psc: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: objectModel!)
let objectContext : NSManagedObjectContext? = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
objectContext?.persistentStoreCoordinator = psc
let arrURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let urlDocument = arrURL[arrURL.count - 1]
let urlStore: URL? = urlDocument.appendingPathComponent("DemoChat.sqlite")
print("Database Path:- \(String(describing: urlStore))")
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
try! psc?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: urlStore, options: options)
return objectContext
}
}
Step 4:- create variable in AppDelegate See below.
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{
var window: UIWindow?
var manageObjectContext : NSManagedObjectContext?
var navController: UINavigationController?
var mainStoryBoard: UIStoryboard = UIStoryboard()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
mainStoryBoard = UIStoryboard(name:"Main", bundle:nil)
manageObjectContext = CoreData.sharedInstance.manageObjectContext()
if UserDefaults.standard.value(forKey: "UserInfo") != nil{
let chatVC : ChatVC = self.mainStoryBoard.instantiateViewController(withIdentifier: "ChatVC") as! ChatVC
navController = UINavigationController(rootViewController: chatVC)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = navController
self.window?.makeKeyAndVisible()
}
// Override point for customization after application launch.
return true
}
}
struct Application {
static let Delegate = UIApplication.shared.delegate as! AppDelegate
}
Now you ready for insert Update and Delete Data from Core Data
Check Below Code
import UIKit
import Firebase
import FirebaseAuth
import CoreData
//import firebase
class ChatVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
var people: [NSManagedObject] = []
@IBOutlet weak var tblChatlist : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
getChatData()
fetchData()
diplaySeletedData()
// Do any additional setup after loading the view.
}
//MARK:- tableView Delegate And dataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dic = people[indexPath.row]
if dic.value(forKey: "id") as! String == userInfo.value(forKey: "Email") as! String
{
let cell = tblChatlist.dequeueReusableCell(withIdentifier: "RightCell") as! RightCell
cell.lblMessgae.text = dic.value(forKeyPath: "message") as! String
cell.lblSenderName.text = dic.value(forKeyPath: "id") as! String
return cell
}
else{
UserDefaults.standard.set(dic.value(forKeyPath: "id") as! String, forKey: "ChatUserName")
UserDefaults.standard.synchronize()
let cell = tblChatlist.dequeueReusableCell(withIdentifier: "LeftCell") as! LeftCell
cell.lblMessgae.text = dic.value(forKeyPath: "message") as! String
cell.lblSenderName.text = dic.value(forKeyPath: "id") as! String
return cell
}
}
//MARK:- Insert data In database
func insertData(_ dic:NSDictionary)
{
let managedContext = Application.Delegate.manageObjectContext
let entity = NSEntityDescription.entity(forEntityName: "ChatHistory", in: managedContext!)!
let person = NSManagedObject(entity: entity, insertInto: managedContext)
person.setValue(dic.value(forKey: "id") as! String, forKeyPath: "id")
person.setValue(dic.value(forKey: "message") as! String, forKeyPath: "message")
do {
try managedContext?.save()
people.append(person)
print(people)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
fetchData()
}
func fetchData()
{
let managedContext = Application.Delegate.manageObjectContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "ChatHistory")
fetchRequest.returnsObjectsAsFaults = false
do {
people = try managedContext?.fetch(fetchRequest) as! [NSManagedObject]
print(people)
self.tblChatlist.reloadData()
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
func diplaySeletedData()
{
let managedContext = Application.Delegate.manageObjectContext
let entityDesc = NSEntityDescription.entity(forEntityName: "ChatHistory", in: managedContext!)!
do {
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDesc
var strColumnName = "id"
let strColumnValue = "watson@gmail.com"
let pred = NSPredicate(format: "id = %@", strColumnValue)
request.predicate = pred
print((try managedContext?.fetch(request))! as NSArray)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
fetchData()
}}
Comments
Post a Comment