【发布时间】:2016-07-01 07:35:23
【问题描述】:
我正在尝试创建一个今天的扩展程序,该扩展程序使用共享应用程序组容器显示来自父应用程序的数据,然后将持久存储添加到上下文中。
- 添加今日扩展目标
- 为父应用和扩展打开应用组并选择同一组
- 添加 Today Extension 作为数据模型和实体的目标成员
- 将持久存储添加到上下文
- 获取对象
我没有收到任何错误,但扩展程序似乎没有获取任何结果。有人对我可能出错的地方有任何建议吗?
这就是我在扩展 TodayViewController 中所做的事情
class TodayViewController: UIViewController, NCWidgetProviding {
var context: NSManagedObjectContext!
@IBOutlet weak var table: UITableView!
var objectsArray = [Objects]()
override func viewDidLoad() {
super.viewDidLoad()
let fileManager = NSFileManager.defaultManager()
var containerPath = fileManager.containerURLForSecurityApplicationGroupIdentifier("group.com.Company.AppName")
containerPath = containerPath?.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
let modelURL = NSBundle.mainBundle().URLForResource("AppName", withExtension: "momd")
let model = NSManagedObjectModel(contentsOfURL: modelURL!)
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model!)
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: containerPath, options: nil)
} catch {
print("yellow")
}
context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
let moc = context
let request = NSFetchRequest(entityName: "Objects")
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
do {
try
self.objectsArray = moc.executeFetchRequest(request) as! [Objects]
print ("objects count \(objectsArray.count)")
} catch {
// failure
print("Fetch failed")
}
self.table.reloadData()
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
//return sectionsArray.count
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.objectsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
cell.textLabel!.textColor = UIColor.whiteColor()
cell.textLabel!.text = self.objectsArray[indexPath.row].title
return cell
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
}
【问题讨论】:
-
我很容易在我的主应用程序和今天的扩展程序之间共享各种数据,其中包含应用程序组和 NSUserDefaults。这可能需要 15 分钟来设置!请参阅此处的第 5 步及以后:glimsoft.com/06/28/ios-8-today-extension-tutorial
标签: ios swift core-data nsfilemanager ios8-today-widget