Skip to content

Instantly share code, notes, and snippets.

@rahul-inspired-iosdeveloper
Last active March 4, 2020 16:58
Show Gist options
  • Save rahul-inspired-iosdeveloper/175f462f5b9feb042be7d28cf4671e01 to your computer and use it in GitHub Desktop.
Save rahul-inspired-iosdeveloper/175f462f5b9feb042be7d28cf4671e01 to your computer and use it in GitHub Desktop.
import Foundation
import CoreData
protocol CoreDataManagerProtocol: class {
func didCartItemAdded() -> ()
}
class CoreDataManager {
//MARK:- Shared Instance
static let sharedCoreDataManager = CoreDataManager()
//MARK: - Properties
weak var coredatamanagerdelegate: CoreDataManagerProtocol?
//MARK:- Custom Accessors
/*!
* @function fetchRecordsForEntity:
*
* @abstract
* Common method to fetch records for entity
*
* @param
* entity name
*/
public func fetchRecordsForEntity(_ entityname: String) -> [NSManagedObject]
{
let managedObjectContext = self.persistentContainer.viewContext
// Create Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityname)
// Helpers
var result = [NSManagedObject]()
do {
// Execute Fetch Request
result = try managedObjectContext.fetch(fetchRequest) as! [NSManagedObject]
} catch {
print("Unable to fetch managed objects for entity \(entityname).")
}
return result
}
//MARK: - User
func saveUserData(userdata: UserDataObject)
{
let userentity = NSEntityDescription.insertNewObject(forEntityName: CoredataEntities.USER_ENTITY,
into: self.persistentContainer.viewContext) as! UserEntity
userentity.uid = userdata.uid
userentity.title = userdata.title
userentity.fullname = userdata.fullname
userentity.email = userdata.email
userentity.phone = userdata.phone
userentity.address = userdata.address
userentity.payment_key = userdata.payment_key
userentity.payment_store_id = userdata.payment_store_id
userentity.payment_trans_test = userdata.payment_trans_test
do {
try self.persistentContainer.viewContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
func updateUserData(userprofiledata: UserProfileDataModel)-> Bool
{
let userentity = self.fetchRecordsForEntity(CoredataEntities.USER_ENTITY).last as? UserEntity
userentity?.fullname = userprofiledata.fullname
userentity?.address = userprofiledata.address
do {
try self.persistentContainer.viewContext.save()
return true
} catch {
return false
}
}
func fetchUserData()->UserEntity?
{
var saveduser: UserEntity?
if self.fetchRecordsForEntity(CoredataEntities.USER_ENTITY).count > 0 {
guard let userentity = self.fetchRecordsForEntity(CoredataEntities.USER_ENTITY).last as? UserEntity else { return saveduser }
saveduser = userentity
}
return saveduser
}
//MARK: - Cart Item
func checkForExistingItem(uid:String) -> CartServiceEntity?
{
let fetchRequest: NSFetchRequest<CartServiceEntity> = CartServiceEntity.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uid == %@", uid)
let context = self.persistentContainer.viewContext
let objects = try! context.fetch(fetchRequest)
return (objects.count > 0) ? objects.last : nil
}
func addAdditionalPrice(subservices: [CircleSubService],session: Double) -> String?
{
var result: String?
for subservice in subservices
{
//---Finding services added in a given session
//guard let cartentity = checkForExistingItem(uid: subservice.uid!), cartentity.session == subservice.session else { continue }
guard let cartentity = checkForExistingItem(uid: subservice.uid!) else { continue }
cartentity.price = subservice.price
cartentity.additional_price_checked = subservice.additional_price_checked!
result = (subservice.additional_price_checked == true) ? AlertMessages.kFrenchStyleAdded : AlertMessages.kFrenchStyleRemoved
}
do {
try self.persistentContainer.viewContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
return result
}
func saveItemToCart(cartitem: CartItemModel) -> Bool
{
var result = true
var cartentity = checkForExistingItem(uid: cartitem.service_uid!)
if cartentity?.uid != nil
{
return result
//--Existing item found
/*let quantity: Int16 = (cartentity?.quantity)!+1
cartentity?.quantity = quantity*/
}
else
{
//--No existing entity in cart
cartentity = NSEntityDescription.insertNewObject(forEntityName: CoredataEntities.CART_SERVICE_ENTITY, into: persistentContainer.viewContext) as? CartServiceEntity
cartentity?.uid = cartitem.service_uid
cartentity?.session = cartitem.session ?? 0.00
cartentity?.service_name = cartitem.service_name
cartentity?.price = cartitem.price
cartentity?.additional_price = cartitem.additional_price
cartentity?.quantity = 1
}
do {
try self.persistentContainer.viewContext.save()
} catch {
result = false
fatalError("Failure to save context: \(error)")
}
coredatamanagerdelegate?.didCartItemAdded()
return result
}
func increaseQuantity(uid: String) -> Bool
{
let cartentity = checkForExistingItem(uid: uid)
cartentity?.quantity += 1
do {
try self.persistentContainer.viewContext.save()
} catch {
return false
}
return true
}
func decreaseQuantity(uid: String) -> Bool
{
let cartentity = checkForExistingItem(uid: uid)
cartentity?.quantity = (cartentity?.quantity == 1) ? 1 : (cartentity?.quantity)!-1
do {
try self.persistentContainer.viewContext.save()
} catch {
return false
}
return true
}
func fetchCartEntities() -> [CartServiceEntity]?
{
guard let cartentities = fetchRecordsForEntity(CoredataEntities.CART_SERVICE_ENTITY) as? [CartServiceEntity]
else { return nil}
return cartentities
}
func fetchCartItems() -> [CartItemModel]?
{
var cartItems: [CartItemModel]?
guard let cartitemsarray = fetchRecordsForEntity(CoredataEntities.CART_SERVICE_ENTITY) as? [CartServiceEntity]
else { return nil}
cartItems = [CartItemModel]()
for item in cartitemsarray
{
let keys = Array(item.entity.attributesByName.keys)
let dict = item.dictionaryWithValues(forKeys: keys)
cartItems?.append(CartItemModel(JSON: dict)!)
}
return cartItems
}
func fetchCartItemsCount() -> Int?
{
var count: Int?
let managedObjectContext = self.persistentContainer.viewContext
// Create Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: CoredataEntities.CART_SERVICE_ENTITY)
do {
count = try managedObjectContext.count(for:fetchRequest)
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
return count
}
func deleteCartItem(uid: String) -> Bool
{
let fetchRequest: NSFetchRequest<CartServiceEntity> = CartServiceEntity.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uid == %@", uid)
let context = self.persistentContainer.viewContext
let objects = try! context.fetch(fetchRequest)
for obj in objects {
context.delete(obj)
}
do {
try context.save()
} catch {
return false
}
coredatamanagerdelegate?.didCartItemAdded()
return true
}
/*!
* @function clearEntityData:
*
* @abstract
* Method to clear data in an entity
*
* @param
* entityName
*/
public func clearEntityData(entityName: String)-> Bool
{
let context = self.persistentContainer.viewContext
// Create Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
// Create Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.execute(batchDeleteRequest)
} catch {
return false
}
return true
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "GlamJamBeautyExpress")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment