Swift library that makes easier to serialize the user's preferences (app's settings) with system User Defaults or Property List file on disk.

Overview

PersistentStorageSerializable

CI Status Carthage compatible Version Swift License

PersistentStorageSerializable is a protocol for automatic serialization and deserialization of Swift class, struct or NSObject descendant object into and from User Defaults or Property List file.

The adopting type properties must be of property list type (String, Data, Date, Int, UInt, Float, Double, Bool, Array or Dictionary of above). If you want to store any other type of object, you should typically archive it to create an instance of Data. The URL properties can be stored in User Defaults storage but not in Plist storage. In the last case, you have to archive it to/from Data.

The PersistentStorageSerializable protocol provides default implementations of init(from:) initializer and persist() function. The library defines two classes of PesistentStorage protocol: UserDefaultsStorage and PlistStorage. Object of one of those types is passed as the argument when calling to init(from:) initializer to specify which storage to be used for serialization/deserialization.

Functions of the PersistentStorageSerializable protocol traverses the adopting type object and gets/sets it's properties values via Reflection library. The NSObject class descendant properties values are get/set via KVC.

How to use

Serialize/Deserialize a struct with User Defaults by using UserDefaultStorage as shown below:

struct Settings: PersistentStorageSerializable {
    var flag = false
    var title = ""
    var number = 1
    var dictionary: [String : Any] = ["Number" : 1, "Distance" : 25.4, "Label" : "Hello"]

    // MARK: Adopt PersistentStorageSerializable
    var persistentStorage: PersistentStorage!
    var persistentStorageKeyPrefix: String! = "Settings"
}

// Init from User Defaults
var mySettings = try! Settings(from: UserDefaultsStorage.standard)

mySettings.flag = true

// Persist into User Defaults
try! mySettings.persist()

To serialize data with Plist file use PlistStorage class:

// Init from plist
let plistUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("storage.plist")

var settingsOnDisk = try! Settings(from: PlistStorage(at: plistUrl))

mySettings.flag = true

// Persist on disk
try! mySettings.persist()

Reading data stored by the previous version of the app

When you have some data persisted in User Defaults by the previous version of the app and want to read that data into a structure you need to provide a mapping between properties names and User Defaults keys by overloading the persistentStorageKey(for:) function.

Say we have following data persisted in User Defaults:

UserDefaults.standard.set("Superhero", forKey: "oldGoogTitle")
UserDefaults.standard.set(true, forKey: "well.persisted.option")

We want those to be serialized with the object of ApplicationConfiguration class.

final class ApplicationConfiguration: PersistentStorageSerializable {
    var title = ""
    var showIntro = false

    // MARK: Adopt PersistentStorageSerializable
    var persistentStorage: PersistentStorage!
    var persistentStorageKeyPrefix: String!
}

// Provide key mapping by overloading `persistentStorageKey(for:)` function.
extension ApplicationConfiguration {
    func persistentStorageKey(for propertyName: String) -> String {
        let keyMap = ["title" : "oldGoogTitle", "showIntro" : "well.persisted.option"]
        return keyMap[propertyName]!
    }
}

// Now we can load data persisted in the storage.
let configuration = try! ApplicationConfiguration(from: UserDefaultsStorage.standard)

print(configuration.title) // prints Superhero
print(configuration.showIntro) // prints true

Example

To run example projects for iOS/macOS, run pod try PersistentStorageSerializable in the terminal.

Requirements

  • Xcode 8.3
  • Swift 3.1

Installation

CocoaPods

PersistentStorageSerializable is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "PersistentStorageSerializable"

and run pods update or pods install.

For Xcode 9, Swift 4 and cocoapods installation, please follow the instruction here.

Carthage

If you use Carthage to manage your dependencies, simply add PersistentStorageSerializable to your Cartfile:

github "IvanRublev/PersistentStorageSerializable"

If you use Carthage to build your dependencies, make sure you have added PersistentStorageSerializable.framework and Reflection.framework to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase.

Author

Copyright (c) 2017, IvanRublev, [email protected]

License

PersistentStorageSerializable is available under the MIT license. See the LICENSE file for more info.

You might also like...
CloudKit, Apple’s remote data storage service, provides a possibility to store app data using users’ iCloud accounts as a back-end storage service.
CloudKit, Apple’s remote data storage service, provides a possibility to store app data using users’ iCloud accounts as a back-end storage service.

CloudKit, Apple’s remote data storage service, provides a possibility to store app data using users’ iCloud accounts as a back-end storage service. He

SwiftPublicSuffixList - Public Suffix List domain name checker in Swift

SwiftPublicSuffixList This library is a Swift implementation of the necessary co

PJAlertView - This library is to make your own custom alert views to match your apps look and feel

PJAlertView - This library is to make your own custom alert views to match your apps look and feel

BucketServer - Small API with SQLite database that saves notes for an iOS appliction called Bucket list

BucketList Server-Side Small API with SQLite database that saves notes for an iO

Easy and beautiful way for a user to pick content, files or images. Written in Objective C
Easy and beautiful way for a user to pick content, files or images. Written in Objective C

##JVTImageFilePicker Description ImageFilesPicker Is a butifuly designed UICompenent for uploading content Preview from recent camera roll Live Camera

PRGTipView is a drop-in solution for adding onboarding tips to your apps
PRGTipView is a drop-in solution for adding onboarding tips to your apps

PRGTipView PRGTipView is a drop-in solution for adding onboarding tips to your apps. It supports: Title, detail and dismissal button Give focus on a p

Server-driven SwiftUI - Maintain iOS apps without making app releases.

ServerDrivenSwiftUI Maintain ios apps without making app releases. Deploy changes to the server and users will receive changes within minutes. This pa

🧡 SQLiteOrm-Swift is an ORM library for SQLite3 built with Swift 5
🧡 SQLiteOrm-Swift is an ORM library for SQLite3 built with Swift 5

🧡 Easy to use SQLite ORM library written with Swift

Owner
Ivan Rublev
Software Crafter, Alchemist, member of Erlang Ecosystem Foundation
Ivan Rublev
Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, configurations and app-state. UserDefaults

Prephirences - Preϕrences Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, co

Eric Marchand 557 Nov 22, 2022
Opensource re-implementation of `defaults(1)`

defaults Opensource re-implementation of defaults(1) Additions: -container - The official defaults(1) does not have appropriate support for containers

Procursus 13 Sep 13, 2022
A light-weight, extensible package for building pixel-perfect iOS settings screens.

SettingsKit A light-weight, extensible package for easily building pixel-perfect iOS settings screens in a pinch. Installation SettingsKit can be inst

Seb Vidal 76 Nov 14, 2022
Shows the issue with swift using an ObjC class which has a property from a swift package.

SwiftObjCSwiftTest Shows the issue with swift using an ObjC class which has a property from a swift package. The Swift class (created as @objc derived

Scott Little 0 Nov 8, 2021
A property wrapper for displaying up-to-date database content in SwiftUI views

@Query Latest release: November 25, 2021 • version 0.1.0 • CHANGELOG Requirements: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 6.0+ • Swift 5.5+ /

Gwendal Roué 102 Dec 29, 2022
⚙️ A tiny property wrapper for UserDefaults. Only 60 lines of code.

⚙️ A tiny property wrapper for UserDefaults. Only 60 lines of code. import Persistent extension UserDefaults { // Optional property @Per

Mezhevikin Alexey 6 Sep 28, 2022
GraphQLite is a toolkit to work with GraphQL servers easily. It also provides several other features to make life easier during iOS application development.

What is this? GraphQLite is a toolkit to work with GraphQL servers easily. It also provides several other features to make life easier during iOS appl

Related Code 2.8k Jan 9, 2023
CRUD is an object-relational mapping (ORM) system for Swift 4+.

CRUD is an object-relational mapping (ORM) system for Swift 4+. CRUD takes Swift 4 Codable types and maps them to SQL database tables. CRUD can create tables based on Codable types and perform inserts and updates of objects in those tables. CRUD can also perform selects and joins of tables, all in a type-safe manner.

PerfectlySoft Inc. 61 Nov 18, 2022
A Swift wrapper for system shell over posix_spawn with search path and env support.

AuxiliaryExecute A Swift wrapper for system shell over posix_spawn with search path and env support. Usage import AuxiliaryExecute AuxiliaryExecute.l

Lakr Aream 11 Sep 13, 2022
Implement Student Admission System using SQlite

StudentAdmissionSQLiteApp Implement Student Admission System using SQlite. #Func

Hardik 2 Apr 27, 2022