Skip to content

Instantly share code, notes, and snippets.

@vhart
Last active November 8, 2022 16:15
Show Gist options
  • Save vhart/f1c1be566c4064dea7ce33712ec714d3 to your computer and use it in GitHub Desktop.
Save vhart/f1c1be566c4064dea7ce33712ec714d3 to your computer and use it in GitHub Desktop.
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)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment