访问iOS 8扩展中的核心数据SQL数据库(在App和Widget扩展之间共享数据) [英] Accessing Core Data SQL Database in iOS 8 Extension (Sharing Data Between App and Widget Extension)

查看:154
本文介绍了访问iOS 8扩展中的核心数据SQL数据库(在App和Widget扩展之间共享数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

无法从今天视图的小部件扩展程序中访问应用程序的核心数据库。

Unable to access application's Core Data database from within a Widget Extension in the Today View.

应用程序本身能够在iOS 8下正常读取和写入数据库,但扩展将无法创建存储,给出错误,无法写入文件。

The app itself is able to read and write to the database as per normal under iOS 8, but the extension will fail to create the store, giving the error, unable to write to file.

日志如下:

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)"

reason = "Failed to create file; code = 2


推荐答案

小部件无法访问NSDocuments目录,这是通常存储其数据库的位置。

Widgets are unable to access the NSDocuments directory, which is where one would normally store their database.

解决方案是先创建应用组

The solution is to first create an App Group

转到:
项目 - 目标 - 应用组 - 添加新容器

Go to: Project - Target - App Groups - Add New Container

命名容器,例如'group.mycontainer'

Name the container, i.e. 'group.mycontainer'

使用容器的同一个名称对Widget的Target重复这个过程。

Repeat the process for the Widget's Target using the same name for the container.

然后将数据库写入您的组容器。

Then write your database to your group container.

因此:

NSURL *storeURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory  inDomains:NSAllDomainsMask] lastObject];
storeURL = [storeURL URLByAppendingPathComponent:@"db.sqlite"];

成为:

NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.mycontainer"];
storeURL = [storeURL URLByAppendingPathComponent:@"db.sqlite"];

初始化商店应该是这样:

And initialising the store should be like so:

NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.mycontainer"];
storeURL = [storeURL URLByAppendingPathComponent:@"db.sqlite"];

NSPersistentStore *store = nil;
store = [coordinator addPersistentStoreWithType:NSSQLiteStoreType
                                  configuration:nil
                                            URL:storeURL
                                        options:nil
                                          error:&error]

这篇关于访问iOS 8扩展中的核心数据SQL数据库(在App和Widget扩展之间共享数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆