nickarthur
1/30/2019 - 1:06 AM

File Handling from an Xcode Playground

File Handling from an Xcode Playground

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

func setUpDemo() {
    let testContents = """
        This is a test
        Emojis follow:
        🚀
        👍🏽

        THE END
        """

    let testFileUrl = playgroundSharedDataDirectory.appendingPathComponent("testFile.txt", isDirectory: false)
    try! testContents.write(to: testFileUrl, atomically: true, encoding: .utf8)
}

setUpDemo()

// MARK: Reading

let testFileUrl = playgroundSharedDataDirectory.appendingPathComponent("testFile.txt")

var fileContents: String?
do {
    fileContents = try String(contentsOf: testFileUrl)
} catch {
    print("Error reading contents: \(error)")
}

fileContents

//or

let testFileContents = try? String(contentsOf: testFileUrl)

// MARK: Writing to a new file

let newFileUrl = playgroundSharedDataDirectory.appendingPathComponent("newFile.txt")
let textToWrite =
"""
I didn't choose the pup life 🐕
The pup life chose me 🐶
❤️
"""

do {
    try textToWrite.write(to: newFileUrl, atomically: true, encoding: .utf8)
} catch {
    print("Error writing: \(error)")
}

let proofOfWrite = try? String(contentsOf: newFileUrl)


// MARK: Updating a file in a not so great way

let catsLine = "\nCats are cute too 🐯"

if let currentContent = try? String(contentsOf: newFileUrl) {
    let newContent = currentContent + catsLine
    do {
        try newContent.write(to: newFileUrl, atomically: true, encoding: .utf8)
    } catch {
        print("Error writing: \(error)")
    }
}

let newContent = try? String(contentsOf: newFileUrl)


// MARK: Updating a file in a much more efficient way

let monkeyLine = "\nAdding a 🐵 to the end of the file via FileHandle"

if let fileUpdater = try? FileHandle(forUpdating: newFileUrl) {
    fileUpdater.seekToEndOfFile()
    fileUpdater.write(monkeyLine.data(using: .utf8)!)
    fileUpdater.closeFile()
}

let contentsAfterUpdatingViaFileHandle = try? String(contentsOf: newFileUrl)


// MARK: Deleting a file
let fileManager = FileManager()

do {
    try fileManager.removeItem(at: newFileUrl)
} catch {
    print("Error deleting file: \(error)")
}

fileManager.fileExists(atPath: newFileUrl.path)


/*
 If error handling is not necessary, any of the do-try-catch blocks can be replaced with `try? _ACTION_HERE_`
 eg. deletion without error handling would become:

 try? fileManager.removeItem(at: newFileUrl)

 */