User’s document directory returning nil with FileManager

I’m trying to write a file locally but no success. When I try to get the user’s document directory it returns nil and I believe this is why my file is not been stored.

Also, I have many doubts of what the “user’s document directory” is supposed to mean. Is it the “Documents/” inside “iCloud Drive” or “on my phone”. Should I be looking in another place instead of “Files” app? I’m using the iPhone simulator.

My code is designed as follow. documentFolderURL, fileURL and url are all nil when debugging.

let documentFolderURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
        let ext: String = type ?? "pdf"
        let name = "extrato." + ext
        let fileURL = documentFolderURL?.appendingPathComponent(name)
        do {
            if let url = fileURL {
                try file.write(to: url, options: .atomic)
            }
        } catch {...}

Answer

It seems that you are creating the file successfully, but you aren’t looking for it in the right place.

You can navigate to the simulator’s User Defaults folder by:

  1. Print the file path of the simulator’s documents directory. print(documentFolderURL) should print something like file:///Users/yourname/Library/Developer/CoreSimulator/Devices/8DAF542C-4B37-41D1-BA43-1D7C2A32E585/data/Containers/Data/Application/63545C94-56F5-3B11-B601-543801BE717A/Documents/

  2. Copy the entire url EXCEPT the leading file:// (in other words, start with /User/yourname

  3. Open your macbook’s Finder app, and press command + shift + g. This will allow you to…(drum roll please)…

  4. Paste in the url to navigate to your simulator’s documents directory.

Your file should be there 🙂