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

查看:16
本文介绍了iOS 8 扩展中访问Core Data 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.

解决办法是先创建一个App Group

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 扩展中访问Core Data SQL 数据库(App 和Widget 扩展之间共享数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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