Skip to content

Instantly share code, notes, and snippets.

View saoudrizwan's full-sized avatar

Saoud Rizwan saoudrizwan

View GitHub Profile
import Disk
do {
try Disk.save(posts, to: .documents, as: "posts.json")
let retrieved = try Disk.retrieve("posts.json", from: .documents, as: [Post].self)
} catch {
// ...
}
// Remove messages.json from Documents Directory
Storage.remove("messages.json", from: .documents)
// Or just clear the Documents Directory entirely
Storage.clear(.documents)
// We can even check if our file exists in the specified directory
if Storage.fileExists("messages.json", in: .documents) {
// we have messages to retrieve
}
let messagesFromDisk = Storage.retrieve("messages.json", from: .documents, as: [Message].self)
var messages = [Message]()
for i in 1...4 {
let newMessage = Message(title: "Message \(i)", body: "...")
messages.append(newMessage)
}
Storage.store(messages, to: .documents, as: "messages.json")
struct Message: Codable {
let title: String
let body: String
}
@saoudrizwan
saoudrizwan / Storage.swift
Last active October 27, 2021 01:51
Helper class to easily store and retrieve Codable structs from/to disk. https://medium.com/@sdrzn/swift-4-codable-lets-make-things-even-easier-c793b6cf29e1
import Foundation
public class Storage {
fileprivate init() { }
enum Directory {
// Only documents and other data that is user-generated, or that cannot otherwise be recreated by your application, should be stored in the <Application_Home>/Documents directory and will be automatically backed up by iCloud.
case documents
sampleImageView.addTapGestureRecognizer {
print("image tapped")
}
@saoudrizwan
saoudrizwan / TapGestureRecognizerWithoutSelector.swift
Last active March 4, 2024 06:45
Easily create tap gesture recognizers for any view using closures as actions instead of selectors.
import UIKit
extension UIView {
// In order to create computed properties for extensions, we need a key to
// store and access the stored property
fileprivate struct AssociatedObjectKeys {
static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
}
func getDocumentsURL() -> URL {
if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
return url
} else {
fatalError("Could not retrieve documents directory")
}
}
let fileManager = FileManager()
func savePostsToDisk(posts: [Post]) {
// 1. Create a url for documents-directory/posts.json
let url = getDocumentsURL().appendingPathComponent("posts.json")
// 2. Endcode our [Post] data to JSON Data
let encoder = JSONEncoder()
do {
let data = try encoder.encode(posts)
// 3. Check if posts.json already exists...