local doc save and iCloud data in same app

I have app that is using container for small settings data and iCloud for larger storage, but I also want to be able to save to local documents folder. When I do that the url that is created is not local docs, but:

path: file:///var/mobile/Containers/Data/Application/85A8B8C9-C0C3-4843-A74C-5A951F593790/Documents/Dialog08:45,%2022%20Feb%202024

Here is code using to save to local docs folder.

func saveDataToFile(data: String) {
    //file will be datetimedialog
    let formatter = DateFormatter()
    formatter.dateFormat = "HH:mm, d MMM y"
    var dateTime = Date.getCurrentDate()
    dateTime = formatter.string(from: Date.now)
    var saveFilename = "Dialog"
    saveFilename.append(dateTime)
    let path = getDocumentsDirectory().appendingPathComponent(saveFilename)
    print("path: \(path)")
    //                        let fileURL = URL(fileURLWithPath: data, relativeTo: path)
    do {
        try data.write(to: path, atomically: true, encoding: String.Encoding.utf8)
    } catch {
        print(error.localizedDescription)
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

Replies

When I do that the url that is created is not local docs

This is iOS, right? If so, that looks like the Documents directory to me. Remember that on iOS every app lives within a container. That’s the /var/mobile/Containers/Data/Application/85A8B8C9-C0C3-4843-A74C-5A951F593790 part of that path. Within that container there are various directories, including the Documents directory.

ps This code probably doesn’t do what you think it does:

formatter.dateFormat = "HH:mm, d MMM y"

QA1480 NSDateFormatter and Internet Dates explains why.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"