How to write a file in storage disk - Swift

Let's say that you have a JSON message from an API and you are trying to avoid unnecessary calls, and decide to store it in a file on your device, here's how to do it:

Check if file is on disk already

Here's a small function to do it:

func checkIfFileOnDiskExists(path: String, extention: String) -> Bool {
        var fileExists: Bool = false
        
        do {
            let fileUrl = try FileManager.default
                .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
                .appendingPathComponent("\(path).\(extention)")
            
            
            if FileManager.default.fileExists(atPath: fileUrl.path) {
                fileExists = true
            } else {
                fileExists = false
            }
            
        } catch {
            print("🛑 Error reading if File exists: \(error)")
        }
        
        return fileExists
    }

which you can call like so:

let isFileOnDisk = checkIfFileOnDiskExists(path: "allCovalentChains", extention: "json")

Write File to Disk

Here's an example of how to write a json file:

func writeVerifiedTokensToDeviceStorage(dataToStore: VerifiedTokensModel) {
    do {
        let fileURL = try FileManager.default
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("allVerifiedTokens.json")
        
        try JSONEncoder().encode(dataToStore)
            .write(to: fileURL)
    } catch {
        print(error)
    }
}

Read File from Disk

func decodeCovalentChainsAvailableStoredInDisk() -> AllChainsClassAModel {
        var chainsAvailable: AllChainsClassAModel?
        
        do {
            let fileURL = try FileManager.default
                .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
                .appendingPathComponent("allCovalentChains.json")

            let data = try Data(contentsOf: fileURL)
            chainsAvailable = try JSONDecoder().decode(AllChainsClassAModel.self, from: data)
            
        } catch {
            print(error)
        }
        
        return chainsAvailable!
    }