简体   繁体   中英

Mac Sandboxing and Temp files

I'm working on sandboxing my applications and I've got a problem because a library that I use creates temporary files when it modifies the original file, eg

When it changes something in "Hello World.txt" it will create a "Hello World_temp.txt" file in the same directory and then when it's finished it will swap both files.

This of course breaks sandboxing rules because you are only allowed to change the source file and not go around creating other files in the folder.

I can't find any recommendations about what to do with temp files, so I'm currently just going to create the temp file in the application's container where I'm allowed to write and then swap the files.. however, that's not great if the application and the file are on different disks as it will involve copying rather than moving.

Is there a place for temporary files that we're allowed to write to?

Best regards,

Frank

On 10.7.3+ (also works out of the sandbox on 10.6) try the NSFileManager method URLForDirectory:inDomain:appropriateForURL:create:error: (docs) . This should give you a temporary directory on a particular volume. Once created you can use replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to switch the files.

Now some uncertainty:

On 10.7 -> 10.7.2 the above method may not work in the sandbox. Instead you can use the function NSTemporaryDirectory() (docs) . You may find that replaceItemAtUrl... also does not work in this case when under the sandbox, in which case write your own code to read/write the temporary back.

NSTemporaryDirectory() works in sandbox. Sample code in Swift:

let path = "\(NSTemporaryDirectory())temp.txt"
"Hello world".writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

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