简体   繁体   中英

Xcode Swift 3.0 macOS (Sierra) app unable to create file, no permission

I'm fairly new to Xcode and Swift. I'm trying to create a file called "file.txt" in my Documents directory and getting the error "You don't have permission to save the file."

Ultimately, I DO NOT want to use the default Documents directory as I'm using FIFinderSyncController to watch everything ("/").

    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)
        }
    }

Log shows:

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

I found the answer here so I thought I would help out. The issue is the limitations of sandbox. If you add

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

To the entitlements file for the target as an Array with strings for the parent folders you want to watch. In my case I just added "/" to watch everything. Here's mine:

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

This will allow you to access everything relative to the folder mentioned.

One warning: it seems (not thoroughly tested) that if there are other FIFinderSyncController's set up (in other apps), they can effect each other.

I had the same issue. I solved it by setting the "App Sandbox" key to "No" in the "Entitlements File". Hope this will help.

在此处输入图片说明

What worked for me in a similar case was to select Read/Write in "User Selected Files" in the Capabilities of the Sandbox.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM