我有一个应用程序(Swift 4,iOS 11),带有应用程序扩展名(键盘)。 App将创建一个json
文件,该文件将保存在App Group目录中。
那是下面的代码:
func testingAppGroups(){
let exampleJson = """
{
"dataRelease": "27.07.2018",
"getDataDate": "02.8.2018"
}
"""
let groupID = "group.myApp"
let fileManger = FileManager.default
guard let groupURL = fileManger.containerURL(forSecurityApplicationGroupIdentifier: groupID) else {
fatalError("APP.ViewController: Could not open shared Group dir")
}
let storagePathURL = groupURL.appendingPathComponent("source.json")
let storagePath = storagePathURL.path
print("Source.json exist : \(fileManger.fileExists(atPath: storagePath))")
print("Path : \(storagePath)")
if !fileManger.fileExists(atPath: storagePath){
fileManger.createFile(atPath: storagePath, contents: exampleJson.data(using: .utf8), attributes: nil)
}
do {
let data = try Data(contentsOf: storagePathURL, options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
print(jsonResult)
} catch {
// handle error
}
}
现在,我尝试从我的App Extension中的App Group目录中读取json
文件:
func testingAppGroups(){
let groupID = "group.myApp"
let fileManger = FileManager.default
guard let groupURL = fileManger.containerURL(forSecurityApplicationGroupIdentifier: groupID) else {
print("APPEX: Could not open shared Group dir")
return
}
let storagePathURL = groupURL.appendingPathComponent("source.json")
let storagePath = storagePathURL.path
do {
let data = try Data(contentsOf: storagePathURL, options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
print(jsonResult)
} catch {
// handle error
}
}
如果我在模拟器中运行我的App,则App Extension会通过控制台输出中止guard
处的功能:
APPEX:无法打开共享的组目录
我怎么了?看来,App Extension无法访问App Group目录。我期待每一个提示:-)