{"id":18839772,"url":"https://github.com/maximbilan/ios-shared-coredata-storage-for-app-groups","last_synced_at":"2025-04-14T07:06:09.550Z","repository":{"id":53701265,"uuid":"44442305","full_name":"maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups","owner":"maximbilan","description":"iOS Shared CoreData Storage for App Groups","archived":false,"fork":false,"pushed_at":"2018-09-22T08:59:05.000Z","size":1508,"stargazers_count":50,"open_issues_count":0,"forks_count":5,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-14T07:04:18.055Z","etag":null,"topics":["app-group","coredata","ios","storage","swift","tutorial","xcode"],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/maximbilan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-10-17T15:18:48.000Z","updated_at":"2023-11-29T10:39:12.000Z","dependencies_parsed_at":"2022-09-18T05:23:54.944Z","dependency_job_id":null,"html_url":"https://github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maximbilan%2FiOS-Shared-CoreData-Storage-for-App-Groups","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maximbilan%2FiOS-Shared-CoreData-Storage-for-App-Groups/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maximbilan%2FiOS-Shared-CoreData-Storage-for-App-Groups/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maximbilan%2FiOS-Shared-CoreData-Storage-for-App-Groups/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/maximbilan","download_url":"https://codeload.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248837280,"owners_count":21169374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["app-group","coredata","ios","storage","swift","tutorial","xcode"],"created_at":"2024-11-08T02:44:01.207Z","updated_at":"2025-04-14T07:06:09.025Z","avatar_url":"https://github.com/maximbilan.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# iOS Shared CoreData Storage for App Groups\n\nSometimes \u003ci\u003eiOS\u003c/i\u003e applications have some extensions, for example \u003ci\u003eToday Extensions\u003c/i\u003e, or \u003ci\u003eApple Watch Extensions\u003c/i\u003e. 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.\n\nFirst of all you need to create app groups for your application. Go to \u003ca href=\"https://developer.apple.com/membercenter/\"\u003eApple Developer Member Center\u003c/a\u003e and register app group. Fill the description and identifier and follow the instructions.\n\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/1.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/2.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/3.png)\n\nAfter that when you will create an identifier for an application or an extension, don’t forget enable the service \u003ci\u003eApp Groups\u003c/i\u003e.\n\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/4.png)\n\nThen go to the application or the extension and edit services. It’s really simple, see the next screenshots:\n\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/5.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/6.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/7.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/8.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/9.png)\n\nAnd 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.\n\nIn the Xcode for the each target enable \u003ci\u003eApp Groups\u003c/i\u003e in target settings.\n\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/10.png)\n\nUse \u003ci\u003eCore Data Storage\u003c/i\u003e class. Implementation of this class see below:\n\n\u003cpre\u003e\nimport Foundation\nimport CoreData\n\npublic class CoreDataStorage {\n\t\n\t// MARK: - Shared Instance\n\t\n\tclass var sharedInstance : CoreDataStorage {\n\t\tstruct Static {\n\t\t\tstatic var onceToken: dispatch_once_t = 0\n\t\t\tstatic var instance: CoreDataStorage? = nil\n\t\t}\n\t\tdispatch_once(\u0026Static.onceToken) {\n\t\t\tStatic.instance = CoreDataStorage()\n\t\t}\n\t\treturn Static.instance!\n\t}\n\t\n\t// MARK: - Initialization\n\t\n\tinit() {\n\t\tNSNotificationCenter.defaultCenter().addObserver(self, selector: \"contextDidSavePrivateQueueContext:\", name: NSManagedObjectContextDidSaveNotification, object: self.privateQueueCtxt)\n\t\tNSNotificationCenter.defaultCenter().addObserver(self, selector: \"contextDidSaveMainQueueContext:\", name: NSManagedObjectContextDidSaveNotification, object: self.mainQueueCtxt)\n\t}\n\t\n\tdeinit {\n\t\tNSNotificationCenter.defaultCenter().removeObserver(self)\n\t}\n\t\n\t// MARK: - Notifications\n\t\n\t@objc func contextDidSavePrivateQueueContext(notification: NSNotification) {\n\t\tif let context = self.mainQueueCtxt {\n\t\t\tself.synced(self, closure: { () -\u003e () in\n\t\t\t\tcontext.performBlock({() -\u003e Void in\n\t\t\t\t\tcontext.mergeChangesFromContextDidSaveNotification(notification)\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t}\n\t\n\t@objc func contextDidSaveMainQueueContext(notification: NSNotification) {\n\t\tif let context = self.privateQueueCtxt {\n\t\t\tself.synced(self, closure: { () -\u003e () in\n\t\t\t\tcontext.performBlock({() -\u003e Void in\n\t\t\t\t\tcontext.mergeChangesFromContextDidSaveNotification(notification)\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t}\n\t\n\tfunc synced(lock: AnyObject, closure: () -\u003e ()) {\n\t\tobjc_sync_enter(lock)\n\t\tclosure()\n\t\tobjc_sync_exit(lock)\n\t}\n\t\n\t// MARK: - Core Data stack\n\t\n\tlazy var applicationDocumentsDirectory: NSURL = {\n\t\t// 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.\n\t\tlet urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)\n\t\treturn urls[urls.count-1]\n\t\t}()\n\t\n\tlazy var managedObjectModel: NSManagedObjectModel = {\n\t\t// 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.\n\t\tlet modelURL = NSBundle.mainBundle().URLForResource(\"TutorialAppGroup\", withExtension: \"momd\")!\n\t\treturn NSManagedObjectModel(contentsOfURL: modelURL)!\n\t\t}()\n\t\n\tlazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {\n\t\t// 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.\n\t\t// Create the coordinator and store\n\t\tvar coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)\n\t\t\n\t\tlet directory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(\"group.com.maximbilan.tutorialappgroup\")!\n\t\t\n\t\tlet url = directory.URLByAppendingPathComponent(\"TutorialAppGroup.sqlite\")\n\t\t\n\t\tdo {\n\t\t\ttry coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)\n\t\t} catch var error as NSError {\n\t\t\tcoordinator = nil\n\t\t\tNSLog(\"Unresolved error \\(error), \\(error.userInfo)\")\n\t\t\tabort()\n\t\t} catch {\n\t\t\tfatalError()\n\t\t}\n\t\tprint(\"\\(coordinator?.persistentStores)\")\n\t\treturn coordinator\n\t\t}()\n\t\n\t// MARK: - NSManagedObject Contexts\n\t\n\tpublic class func mainQueueContext() -\u003e NSManagedObjectContext {\n\t\treturn self.sharedInstance.mainQueueCtxt!\n\t}\n\t\n\tpublic class func privateQueueContext() -\u003e NSManagedObjectContext {\n\t\treturn self.sharedInstance.privateQueueCtxt!\n\t}\n\t\n\tlazy var mainQueueCtxt: NSManagedObjectContext? = {\n\t\t// 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.\n\t\tvar managedObjectContext = NSManagedObjectContext(concurrencyType:.MainQueueConcurrencyType)\n\t\tmanagedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator\n\t\treturn managedObjectContext\n\t\t}()\n\t\n\tlazy var privateQueueCtxt: NSManagedObjectContext? = {\n\t\t// 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.\n\t\tvar managedObjectContext = NSManagedObjectContext(concurrencyType:.PrivateQueueConcurrencyType)\n\t\tmanagedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator\n\t\treturn managedObjectContext\n\t\t}()\n\t\n\t// MARK: - Core Data Saving support\n\t\n\tpublic class func saveContext(context: NSManagedObjectContext?) {\n\t\tif let moc = context {\n\t\t\tif moc.hasChanges {\n\t\t\t\tdo {\n\t\t\t\t\ttry moc.save()\n\t\t\t\t} catch {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n\nextension NSManagedObject {\n\t\n\tpublic class func findAllForEntity(entityName: String, context: NSManagedObjectContext) -\u003e [AnyObject]? {\n\t\tlet request = NSFetchRequest(entityName: entityName)\n\t\tlet result: [AnyObject]?\n\t\tdo {\n\t\t\tresult = try context.executeFetchRequest(request)\n\t\t} catch let error as NSError {\n\t\t\tprint(error)\n\t\t\tresult = nil\n\t\t}\n\t\treturn result\n\t}\n}\n\u003c/pre\u003e\n\n\u003ci\u003eCoreData\u003c/i\u003e class for working with your shared storage, also \u003ci\u003eNSManagedObject\u003c/i\u003e extension for fetching data from the entity.\n\nI provide samples for iOS application, \u003ci\u003eToday Extension\u003c/i\u003e and \u003ci\u003eWatchKit\u003c/i\u003e app. See the screenshots:\n\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/11.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/12.png)\n![alt tag](https://raw.github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups/master/screenshots/13.png)\n\nYou need to create a context and CoreData object:\n\n\u003cpre\u003e\nlet context = CoreDataStorage.mainQueueContext()\nvar counter: Counter?\n\u003c/pre\u003e\n\nFor fetching data please use the following code:\n\n\u003cpre\u003e\nfunc fetchData() {\n\tself.context.performBlockAndWait{ () -\u003e Void in\n\t\tlet counter = NSManagedObject.findAllForEntity(\"Counter\", context: self.context)\n\t\tif (counter?.last != nil) {\n\t\t\tself.counter = (counter?.last as! Counter)\n\t\t}\n\t\telse {\n\t\t\tself.counter = (NSEntityDescription.insertNewObjectForEntityForName(\"Counter\", inManagedObjectContext: self.context) as! Counter)\n\t\t\tself.counter?.title = \"Counter\"\n\t\t\tself.counter?.value = 0\n\t\t}\n\t\t\n\t\tself.updateUI()\n\t}\n}\n\u003c/pre\u003e\n\nFor saving a context:\n\n\u003cpre\u003e\nCoreDataStorage.saveContext(self.context)\n\u003c/pre\u003e\n\nThe full code you can find in this repository. Please feel free. Happy coding!\n\n\u003cb\u003eNOTE:\u003c/b\u003e 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 \u003ci\u003eCoreData\u003c/i\u003e datastore is small and changes infrequently you could potentially use the transferFile \u003ci\u003eWatchConnectivity API\u003c/i\u003e to transfer the whole store each time it changes.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaximbilan%2Fios-shared-coredata-storage-for-app-groups","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaximbilan%2Fios-shared-coredata-storage-for-app-groups","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaximbilan%2Fios-shared-coredata-storage-for-app-groups/lists"}