我们目前正在开发一个 iOS10 应用程序,包括“消息扩展”。
为了在 App 和 Extension 之间共享 CoreDatas 持久性 store.sqlite
,我们使用了一个共享的“Apple App Group”目录,它工作正常。
现在,由于调试原因,我们必须亲自访问商店,但找不到目录。 Apps 容器目录完全是空的,这是有道理的。但是如何下载我们的数据库呢?我们是否必须以某种方式以编程方式将其复制到可访问的位置?
总结一下:
- 我们已经使用了 CoreData,它将 model.sqlite 存储在我们的共享目录中。
- 一切正常。
- 我们要归档的是将数据库下载到我们的计算机上。
如果没有共享目录,我们可以使用 Xcode->Devices 简单地从设备下载 App 容器。但是由于我们确实使用共享目录,所以 .sqlite 数据库不在容器内。
问题: 我们如何将.sqlite 数据库从设备下载到我们的计算机?
最佳答案
2018-10-12 编辑:更新了 Swift 4.x (Xcode 10) 的代码。 (保留旧版本以供引用。)
在 Swift 4.x 中:
let sharedContainerURL :URL? = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.etc.etc")
// replace "group.etc.etc" above with your App Group's identifier
NSLog("sharedContainerURL = \(String(describing: sharedContainerURL))")
if let sourceURL :URL = sharedContainerURL?.appendingPathComponent("store.sqlite") {
if let destinationURL :URL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("copyOfStore.sqlite") {
try! FileManager().copyItem(at: sourceURL, to: destinationURL)
}
}
在旧版本的 Swift 中(可能是 Swift 2.x):
let sharedContainerURL :NSURL? = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.etc.etc") // replace "group.etc.etc" with your App Group's identifier
NSLog("sharedContainerURL = \(sharedContainerURL)")
if let sourceURL :NSURL = sharedContainerURL?.URLByAppendingPathComponent("store.sqlite")
{
if let destinationURL :NSURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0].URLByAppendingPathComponent("copyOfStore.sqlite")
{
try! NSFileManager().copyItemAtURL(sourceURL, toURL: destinationURL)
}
}
类似上面的内容将从应用程序组的共享容器中获取一个文件到应用程序的文档目录中。从那里,您可以使用 Xcode > Window > Devices 将其发送到您的计算机。
在 Info.plist
中将 UIFileSharingEnabled
设置为 YES
后,您还可以使用 iTunes 文件共享从应用程序的文档目录中检索文件文件,但请记住,这也会将目录的内容暴露给用户。不过,对于开发/调试目的应该没问题。
关于ios - 如何查找 Apple App Group 共享目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39836831/