iOS create file
Asked Answered
L

2

7

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).

Lush answered 16/1, 2012 at 13:43 Comment(0)
B
14

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];
Brawl answered 16/1, 2012 at 13:49 Comment(1)
What a blunder. I overlooked NSFileManager. Anyway, thanks for your effort.Lush
I
0

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)")
    }
}
Inbred answered 30/4, 2019 at 3:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.