How to write a file in storage disk - Swift

Oct 14, 2021 1 min read
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!
    }
Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.