Search code examples
iosswiftfilensfilemanager

Text File is not being created in applicationSupport folder in Swift


I am trying to input a sting into a text file, but the function createFile(path:contents:attributes) returns false indicating that the file is not being created. I am tiring to create in teh application-support directory, but even if I try the documentDirecorty I get the same result showing that the file was not created. Not sure what I am doing wrong.

let filePin = "userPass.txt"
let _string = "password"
let encrypted = _string.toHexString()
let fileMngr = FileManager.default
let path = fileMngr.urls(for: FileManager.SearchPathDirectory.applicationSupportDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last?.appendingPathComponent(self.filePin)
if let data = encrypted.data(using: String.Encoding.utf8) {
    if fileMngr.createFile(atPath: (path?.absoluteString)!, contents: data, attributes: nil){
        print("The file was created")
    }
    else {
        print("File was not created")
    }
}

Should be getting "The file was created" but instead get "File is not created"


Solution

  • Apart from the wrong API absoluteString the application support folder might not exist.

    This is more reliable

    let string = "password"
    let encrypted = string.toHexString()
    let fileManager = FileManager.default
    do {
        let applicationSupportDirectory = try fileManager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let fileUrl = applicationSupportDirectory.appendingPathComponent(self.filePin)
        let data = Data(encrypted.utf8)
        try data.write(to: fileUrl)
        print("The file was created")
    } catch {
        print(error, "File was not created")
    }