Mac Sandboxing and Temp Files

I am working on the sandbox of my applications and I have a problem because the library I use creates temporary files when it modifies the source file, for example.

When he changes something in "Hello World.txt", he will create the file "Hello World_temp.txt" in the same directory, and then when he finishes, he will replace both files.

This, of course, violates the rules of the sandbox, because you are allowed to modify the source file, and not create other files in the folder.

I can’t find any recommendations on what to do with temporary files, so now I’m going to create a temporary file in the application container, where I am allowed to write and then change the files .. however, that’s not very good if the application and file are on different drives, because it will include copying , not moving.

Is there room for temporary files that we are allowed to write to?

Respectfully,

Franc

+4
source share
2 answers

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

Now some uncertainty:

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

+8
source

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

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

Source: https://habr.com/ru/post/1402672/


All Articles