Xcode Swift 3.0 macOS(Sierra)应用程序无法创建文件,没有权限

Joh*_*ith 5 xcode swift macos-sierra xcode8

我对Xcode和Swift很新.我正在尝试在我的Documents目录中创建一个名为"file.txt"的文件,并收到错误"您没有权限保存文件".

最终,我不想使用默认的Documents目录,因为我正在使用FIFinderSyncController来监视所有内容("/").

    let targetFile = (FIFinderSyncController.default().targetedURL()?.path)! + "/file.txt"

    NSLog("%@", targetFile as NSString)

    let fileManager = FileManager.default
    if fileManager.fileExists( atPath: (targetFile) ) == false {

        do {
            let targetString = (FIFinderSyncController.default().targetedURL()?.path)! + "/Untitled.txt"

            NSLog("%@", targetString as NSString)

            let fileManager = FileManager.default

            if fileManager.fileExists( atPath: targetString ) == false {
                let content = "" // Just creating empty file.

                //writing
                try content.write(toFile: targetString, atomically: false, encoding: String.Encoding.utf8)

                //reading
                let readingText = try NSString(contentsOfFile: targetString, encoding: String.Encoding.utf8.rawValue)

                NSLog("%@", readingText as NSString)
            }
        }
        catch {
            print(error.localizedDescription)
        }
    }
Run Code Online (Sandbox Code Playgroud)

日志显示:

2017-04-06 13:35:46.450077-0700 Open New Text File[5177:1035580]     /Users/david/Documents/file.txt
2017-04-06 13:35:46.450257-0700 Open New Text File[5177:1035580]     /Users/david/Documents/file.txt
You don’t have permission to save the file “file.txt” in the folder “Documents”.
Run Code Online (Sandbox Code Playgroud)

Joh*_*ith 6

我在这里找到了答案,所以我想我会帮忙.问题是沙箱的局限性.如果你添加

com.apple.security.temporary-exception.files.home-relative-path.read-write
Run Code Online (Sandbox Code Playgroud)

将目标的权利文件作为包含要查看的父文件夹的字符串的数组.在我的情况下,我只是添加"/"来观看一切.这是我的:

<key>com.apple.security.temporary-exception.files.home-relative-path.read-write</key>
<array>
    <string>/</string>
</array>
Run Code Online (Sandbox Code Playgroud)

这将允许您访问相对于提到的文件夹的所有内容.

一个警告:似乎(未经过彻底测试)如果有其他的FIFinderSyncController设置(在其他应用程序中),它们可以相互影响.


Cue*_*Cue 5

在类似情况下对我有用的是在沙箱的功能中的“用户选择的文件”中选择读/写。

在此处输入图片说明