[英]How to share data with containing app using NSUserDefaults ? - Today Extension Widget
I am trying to create a Today Extension Widget which displays stored data in the widget. 我正在尝试创建一个Today Extension Widget ,它在窗口小部件中显示存储的数据。
Here's what I have done; 这就是我所做的;
Now I have hit a road block, I am unsure the best way to retrieve and display a simple array of fetched data. 现在我遇到了障碍,我不确定检索和显示简单的获取数据数组的最佳方法。
There is very little Swift tutorials and they often do not use core data. Swift教程非常少,他们通常不使用核心数据。
In the main app project I fetch the array. 在主应用程序项目中,我获取数组。
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let request = NSFetchRequest(entityName: "Objects")
do {
try
self.objectsArray = moc.executeFetchRequest(request) as! [Objects]
} catch {
}
How can I use NSUserDefaults
to store the objects array and then use in the today widget extension ? 如何使用
NSUserDefaults
存储对象数组,然后在今天的小部件扩展中使用? Or Even an array of string values. 或者甚至是一串字符串值。
1) Get url to your database 1)获取数据库的URL
var containerPath: String = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(YOUR_SECURITY_APP_GROUP).path
var sqlitePath: String = "(containerPath)/("database.sqlite")"
2) Create Persistent Store Coordinator as you do in parent app. 2)像在父应用程序中一样创建持久性存储协调器。
3) Set it for your Managed Object context 3)为您的托管对象上下文设置它
context = NSManagedObjectContext()
context.persistentStoreCoordinator = coordinator
4) Retrieve objects as you do in your parent app 4)像在父应用程序中一样检索对象
let moc = context
let request = NSFetchRequest(entityName: "Objects")
do {
try self.objectsArray = moc.executeFetchRequest(request) as! [Objects]
} catch {}
If you set up the App Groups correct and added the same group for both Application and Extension you can use NSUserDefaults. 如果您正确设置应用程序组并为应用程序和扩展程序添加了相同的组,则可以使用NSUserDefaults。 Just for instance, to write something from the app, you need:
例如,要从应用程序中编写内容,您需要:
static func setSharedScoreNumber(score: Int) {
let defaults = UserDefaults(suiteName: "group.bubblewrapSharedDefaults") // this is the name of the group we added in "App Groups"
defaults?.set(String(score), forKey: "score")
defaults?.synchronize()
}
And to read from Todays Extension: 并阅读今日推广:
private func getScore() -> String {
let defaults = UserDefaults(suiteName: "group.bubblewrapSharedDefaults")
defaults?.synchronize()
return String(describing: defaults!.object(forKey: "score") ?? "0")
}
Here's the complete guide how to do so. 这是完整的指南如何做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.