Ios create file

I am trying to open a file for writing to it. The file may not exist.

I found that [NSFileHandle fileHandleForWritingAtPath:filePath] returns nil if the file does not exist. Having googled, I found code snippets like this

 [[NSData data] writeToFile:filePath atomically:YES] 

which, I think, guarantees the existence of the file before opening it.

My questions are: is the last line of code the recommended way to create a file? It seems strange that NSFileHandle does not have a routine to create a new file (and can only work with existing files).

+6
source share
2 answers

NSFileHandle may not have a method for creating the file, but NSFileManager has it. Have you looked at this class?

This works fine for me, however note that it will overwrite the same file every time

 NSString *cachesFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *file = [cachesFolder stringByAppendingPathComponent:@"testfile"]; [[NSData data] writeToFile:file options:NSDataWritingAtomic error:nil]; 
+14
source

In Swift 4.x & 5.0, you can do it like this:

 let yourData = Data() // the data to write let cachesFolderPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first if let path = cachesFolderPath { let url = URL(fileURLWithPath: path).appendingPathComponent("xxx-cache") do { try yourData.write(to: url) } catch { print("writing failed: \(error.localizedDescription)") } } 
0
source

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


All Articles