无法从App Extension访问App Group目录

时间:2018-08-21 10:45:08

标签: swift ios-app-extension ios-app-group

我有一个应用程序(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目录。我期待每一个提示:-)

0 个答案:

没有答案