Reputation: 3435
I am trying to open a file for writing into it. The file may not exist.
I found that [NSFileHandle fileHandleForWritingAtPath:filePath]
returns nil if file does not exist.
Having googled, I found code snippets like this
[[NSData data] writeToFile:filePath atomically:YES]
which, I guess, ensures file existance before opening it.
My questions is: is the latter code line recommended way of file creation? It seems strange that NSFileHandle has no routine to create a new file (and only can deal with existing files).
Upvotes: 7
Views: 9655
Reputation: 3885
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)")
}
}
Upvotes: 0
Reputation: 26952
NSFileHandle
might not have a method to create a file, but NSFileManager
has one. Have you looked at that class?
This works fine for me, however note that it will overwrite the same file each time
NSString *cachesFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [cachesFolder stringByAppendingPathComponent:@"testfile"];
[[NSData data] writeToFile:file options:NSDataWritingAtomic error:nil];
Upvotes: 14