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

标签 swift xcode xcode8 macos-sierra

我对 Xcode 和 Swift 还很陌生。我试图在我的文档目录中创建一个名为“file.txt”的文件,但收到错误消息“您没有保存该文件的权限。”

最终,我不想使用默认的文档目录,因为我正在使用 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)
        }
    }

日志显示:

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”.

最佳答案

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

com.apple.security.temporary-exception.files.home-relative-path.read-write

目标的权利文件作为一个数组,其中包含您要观看的父文件夹的字符串。在我的例子中,我只是添加了“/”来观看所有内容。这是我的:

<key>com.apple.security.temporary-exception.files.home-relative-path.read-write</key>
<array>
    <string>/</string>
</array>

这将允许您访问与提到的文件夹相关的所有内容。

一个警告:似乎(未经过全面测试)如果设置了其他 FIFinderSyncController(在其他应用程序中),它们会相互影响。

关于swift - Xcode Swift 3.0 macOS (Sierra) 应用程序无法创建文件,没有权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43265458/

相关文章:

ios - 设备无法运行 arm64 的可执行文件。 - Xcode 8 测试版

ios - 终端获取URL后如何将数据传递到tableview? swift 5

swift - Cloudant 查询以返回 2 个字段相等的记录

iOS Swift 3-UIDatePicker

apple-push-notifications - 注册推送通知 Swift 3 + iOS 10

ios - Xcode 版本 8 中的代码签名问题

iOS swift 为什么两种类型的闭包不能添加到数组

ios - 在没有 Xcode 的情况下,在 Flutter 中将 GoogleService-Info.plist 保存在哪里?

ios - 使用 Swift 5 截取屏幕截图返回黑色图像而不是应用程序的屏幕

ios - 带有 "Release: Fastest, Smallest [-Os]"的 Xcode 8 有一些奇怪的问题,并且在某些情况下无法正常运行