0

I need to save some data in my iOS App. To do so I want to create a basic text file that I can then call again from elsewhere in my App. But my create File request always returns false.

let fileMang = FileManager.default
let home = NSHomeDirectory()
let filePath = String(home) + "/AppData/Documents/points.txt"
if fileMang.fileExists(atPath: filePath) {
    do {
        try fileMang.removeItem(atPath: filePath)
    }
    catch {}
}
let test = fileMang.createFile(atPath: filePath, contents: "0, 0, 0".data(using: String.Encoding.utf8), attributes: nil)
print(test)

The "0, 0, 0" String is only supposed to be a placeholder. My actual data is written to the file later on. I tried to create an empty file at first with Data.init() but this did not work either so I switched to this placeholder. Ideally though the new file would be empty.

Dario K.
  • 25
  • 1
  • 7
  • Did you have a look here? https://stackoverflow.com/questions/40007390/how-to-create-text-file-for-writing – Teetz Oct 09 '18 at 14:48
  • Read more about FileManager and directories it can give you. Mind that iOS simulator is running on MacOS that have different disk permission and accesses, so generally it is possible to access any file of Mac OS from Simulator, but it is not true for iOS – MichaelV Oct 09 '18 at 14:58
  • Why are you trying to create a "placeholder" file before you actually need to write to the file? Do you intend to keep appending to this file over time? – rmaddy Oct 09 '18 at 15:02

2 Answers2

0

Don't use hardcoded paths like "AppData/Documents", instead it's better to ask the system for e.g. the path to the app support directory using

let appSupportDir = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let filePath = appSupportDir.appendingPathComponent("points.txt").path 
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • It should be noted that in iOS, the Application Support directory does not exist by default. It's a good path to use but you need to use `FileManager createDirectory` to create it if it doesn't exist. – rmaddy Oct 09 '18 at 15:05
  • With some small changes this did solve my problem, thank you! For anyone interested, the code snippet from my original post now looks like this: https://gist.github.com/dklenke/64345cad2b853dd321d35b997dacea61 – Dario K. Oct 09 '18 at 15:07
  • @rmaddy that's why I've suggested using the version of the API that has the `create` parameter :) – Gereon Oct 09 '18 at 15:09
  • And so you did. Sorry, missed that at the end. – rmaddy Oct 09 '18 at 15:10
0

You could also do something like this:

do {
    try data.write(to: URL(fileURLWithPath: path), options: .atomic)
}
catch {
    print(error)
}

Taken from: Is there a writeToFile equivalent for Swift 3's 'Data' type?

Simon Germain
  • 6,834
  • 1
  • 27
  • 42