All Projects → maximbilan → iOS-Shared-CoreData-Storage-for-App-Groups

maximbilan / iOS-Shared-CoreData-Storage-for-App-Groups

Licence: MIT license
iOS Shared CoreData Storage for App Groups

Programming Languages

swift
15916 projects

Projects that are alternatives of or similar to iOS-Shared-CoreData-Storage-for-App-Groups

eks-nvme-ssd-provisioner
EKS NVMe SSD provisioner for Amazon EC2 Instance Stores
Stars: ✭ 50 (+4.17%)
Mutual labels:  storage
storage
Multi-Factor Least Squares Monte Carlo energy storage valuation model (Python and .NET).
Stars: ✭ 24 (-50%)
Mutual labels:  storage
storage
Storage Standard
Stars: ✭ 92 (+91.67%)
Mutual labels:  storage
SuperCoreAPI
The best way to create a Plugin
Stars: ✭ 17 (-64.58%)
Mutual labels:  storage
storage-box
Intuitive and easy-to-use storage box.
Stars: ✭ 26 (-45.83%)
Mutual labels:  storage
azure-storage
Azure Storage module for Nest framework (node.js) ☁️
Stars: ✭ 71 (+47.92%)
Mutual labels:  storage
CoreDataToSwiftUI
Rule based CRUD CoreData Frontends for SwiftUI
Stars: ✭ 18 (-62.5%)
Mutual labels:  coredata
blobit
BlobIt - a Distributed Large Object Storage
Stars: ✭ 29 (-39.58%)
Mutual labels:  storage
beegfs-csi-driver
The BeeGFS Container Storage Interface (CSI) driver provides high performing and scalable storage for workloads running in Kubernetes.
Stars: ✭ 32 (-33.33%)
Mutual labels:  storage
SimpleStorage
💾 Simplify Android Storage Access Framework for file management across API levels.
Stars: ✭ 498 (+937.5%)
Mutual labels:  storage
laravel-ovh
Wrapper for OVH Object Storage integration with laravel
Stars: ✭ 30 (-37.5%)
Mutual labels:  storage
storage-abstraction
Provides an abstraction layer for interacting with a storage; the storage can be local or in the cloud.
Stars: ✭ 36 (-25%)
Mutual labels:  storage
DBMSology
The Paper List on Design and Implmentation of System Software
Stars: ✭ 67 (+39.58%)
Mutual labels:  storage
Floppy
Fast object key value storage for Java with much support for Android
Stars: ✭ 82 (+70.83%)
Mutual labels:  storage
sqlweb
SqlWeb is an extension of JsStore which allows to use sql query for performing database operation in IndexedDB.
Stars: ✭ 38 (-20.83%)
Mutual labels:  storage
file-handling
File Handling Helper
Stars: ✭ 14 (-70.83%)
Mutual labels:  storage
gcp-storage-emulator
Local emulator for Google Cloud Storage
Stars: ✭ 43 (-10.42%)
Mutual labels:  storage
Project01-C-User-Event-Collector
💜🎷 네이버 VIBE 사용자 이벤트 수집기 🎷💜
Stars: ✭ 21 (-56.25%)
Mutual labels:  coredata
ScopedStorageDemo
medium.com/better-programming/all-you-need-to-know-about-scoped-storage-in-android-10-e621f40bc8b9
Stars: ✭ 44 (-8.33%)
Mutual labels:  storage
storage
Mongoose-like schema validation, collections and documents on browser (client-side)
Stars: ✭ 17 (-64.58%)
Mutual labels:  storage

iOS Shared CoreData Storage for App Groups

Sometimes iOS applications have some extensions, for example Today Extensions, or Apple Watch Extensions. And sometimes no sense to implement a data storage for the every target. In this post I tell how to create one data storage for iOS application and his extensions.

First of all you need to create app groups for your application. Go to Apple Developer Member Center and register app group. Fill the description and identifier and follow the instructions.

alt tag alt tag alt tag

After that when you will create an identifier for an application or an extension, don’t forget enable the service App Groups.

alt tag

Then go to the application or the extension and edit services. It’s really simple, see the next screenshots:

alt tag alt tag alt tag alt tag alt tag

And please, perform this procedure for all extensions of the group. It’s all settings, now open the Xcode and let’s go to write code.

In the Xcode for the each target enable App Groups in target settings.

alt tag

Use Core Data Storage class. Implementation of this class see below:

import Foundation
import CoreData

public class CoreDataStorage {
	
	// MARK: - Shared Instance
	
	class var sharedInstance : CoreDataStorage {
		struct Static {
			static var onceToken: dispatch_once_t = 0
			static var instance: CoreDataStorage? = nil
		}
		dispatch_once(&Static.onceToken) {
			Static.instance = CoreDataStorage()
		}
		return Static.instance!
	}
	
	// MARK: - Initialization
	
	init() {
		NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSavePrivateQueueContext:", name: NSManagedObjectContextDidSaveNotification, object: self.privateQueueCtxt)
		NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveMainQueueContext:", name: NSManagedObjectContextDidSaveNotification, object: self.mainQueueCtxt)
	}
	
	deinit {
		NSNotificationCenter.defaultCenter().removeObserver(self)
	}
	
	// MARK: - Notifications
	
	@objc func contextDidSavePrivateQueueContext(notification: NSNotification) {
		if let context = self.mainQueueCtxt {
			self.synced(self, closure: { () -> () in
				context.performBlock({() -> Void in
					context.mergeChangesFromContextDidSaveNotification(notification)
				})
			})
		}
	}
	
	@objc func contextDidSaveMainQueueContext(notification: NSNotification) {
		if let context = self.privateQueueCtxt {
			self.synced(self, closure: { () -> () in
				context.performBlock({() -> Void in
					context.mergeChangesFromContextDidSaveNotification(notification)
				})
			})
		}
	}
	
	func synced(lock: AnyObject, closure: () -> ()) {
		objc_sync_enter(lock)
		closure()
		objc_sync_exit(lock)
	}
	
	// MARK: - Core Data stack
	
	lazy var applicationDocumentsDirectory: NSURL = {
		// The directory the application uses to store the Core Data store file. This code uses a directory named 'Bundle identifier' in the application's documents Application Support directory.
		let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
		return urls[urls.count-1]
		}()
	
	lazy var managedObjectModel: NSManagedObjectModel = {
		// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
		let modelURL = NSBundle.mainBundle().URLForResource("TutorialAppGroup", withExtension: "momd")!
		return NSManagedObjectModel(contentsOfURL: modelURL)!
		}()
	
	lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
		// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
		// Create the coordinator and store
		var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
		
		let directory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.maximbilan.tutorialappgroup")!
		
		let url = directory.URLByAppendingPathComponent("TutorialAppGroup.sqlite")
		
		do {
			try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
		} catch var error as NSError {
			coordinator = nil
			NSLog("Unresolved error \(error), \(error.userInfo)")
			abort()
		} catch {
			fatalError()
		}
		print("\(coordinator?.persistentStores)")
		return coordinator
		}()
	
	// MARK: - NSManagedObject Contexts
	
	public class func mainQueueContext() -> NSManagedObjectContext {
		return self.sharedInstance.mainQueueCtxt!
	}
	
	public class func privateQueueContext() -> NSManagedObjectContext {
		return self.sharedInstance.privateQueueCtxt!
	}
	
	lazy var mainQueueCtxt: NSManagedObjectContext? = {
		// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
		var managedObjectContext = NSManagedObjectContext(concurrencyType:.MainQueueConcurrencyType)
		managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
		return managedObjectContext
		}()
	
	lazy var privateQueueCtxt: NSManagedObjectContext? = {
		// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
		var managedObjectContext = NSManagedObjectContext(concurrencyType:.PrivateQueueConcurrencyType)
		managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
		return managedObjectContext
		}()
	
	// MARK: - Core Data Saving support
	
	public class func saveContext(context: NSManagedObjectContext?) {
		if let moc = context {
			if moc.hasChanges {
				do {
					try moc.save()
				} catch {
				}
			}
		}
	}
	
}

extension NSManagedObject {
	
	public class func findAllForEntity(entityName: String, context: NSManagedObjectContext) -> [AnyObject]? {
		let request = NSFetchRequest(entityName: entityName)
		let result: [AnyObject]?
		do {
			result = try context.executeFetchRequest(request)
		} catch let error as NSError {
			print(error)
			result = nil
		}
		return result
	}
}

CoreData class for working with your shared storage, also NSManagedObject extension for fetching data from the entity.

I provide samples for iOS application, Today Extension and WatchKit app. See the screenshots:

alt tag alt tag alt tag

You need to create a context and CoreData object:

let context = CoreDataStorage.mainQueueContext()
var counter: Counter?

For fetching data please use the following code:

func fetchData() {
	self.context.performBlockAndWait{ () -> Void in
		let counter = NSManagedObject.findAllForEntity("Counter", context: self.context)
		if (counter?.last != nil) {
			self.counter = (counter?.last as! Counter)
		}
		else {
			self.counter = (NSEntityDescription.insertNewObjectForEntityForName("Counter", inManagedObjectContext: self.context) as! Counter)
			self.counter?.title = "Counter"
			self.counter?.value = 0
		}
		
		self.updateUI()
	}
}

For saving a context:

CoreDataStorage.saveContext(self.context)

The full code you can find in this repository. Please feel free. Happy coding!

NOTE: In watchOS 2 and higher you should have to maintain two separate data stores. The group identifier is not working in this case. If either side is a "read-only" client and the CoreData datastore is small and changes infrequently you could potentially use the transferFile WatchConnectivity API to transfer the whole store each time it changes.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].