Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, e.g.

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

like image 742
Frank R. Avatar asked Mar 21 '12 14:03

Frank R.


2 Answers

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.

like image 181
CRD Avatar answered Oct 22 '22 07:10

CRD


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

let path = "\(NSTemporaryDirectory())temp.txt"
"Hello world".writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
like image 30
Tyler Liu Avatar answered Oct 22 '22 08:10

Tyler Liu