CodableCloudKit allows you to easily save and retrieve Codable objects to iCloud Database (CloudKit)

Overview

CodableCloudKit Logo

Swift 5.0 Version Platform

CodableCloudKit

CodableCloudKit allows you to easily save and retrieve Codable objects to iCloud Database (CloudKit)

Features

  • ℹ️ Add CodableCloudKit features

Example

The example application is the best way to see CodableCloudKit in action. Simply open the CodableCloudKit.xcodeproj and run the Example scheme.

Installation

CocoaPods

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

pod 'CodableCloudKit'

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate CodableCloudKit into your project manually. Simply drag the Sources Folder into your Xcode project.

Usage

Before you start, you have to enable CloudKit in your app.

When you did that, go to your dashboard and create all the record types you need to save. In this example, we will use User. Add a new Field to User with value as field name and String as field type. All of your objects will be saved as a String.

After that, go in INDEXES, you have to add 2 indexes to your records. The first one is value with QUERYABLE as index type. The second one is modifiedAt with SORTABLE as index type.

Now, we should be good.

Example

Let's say you have a User model you want to sync to CloudKit. This is what the model would look like:

class User: CodableCloud {
    let username: String
}

//OR

class User: CodableCloud /* OR Codable & Cloud */ {
    let username: String

    enum CodingKeys: String, CodingKey {
        case username
    }

    required init(username: String) {
        self.username = username
        super.init()
    }

    required override init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.username = try container.decode(String.self, forKey: .username)
        try super.init(from: decoder)
    }
}

CodableCloud is a typealias of Codable & Cloud.

Save

func saveInCloud(_ database: CKDatabase = CKContainer.default().privateCloudDatabase, 
                 _ completion: ResultCompletion<CKRecord>? = nil)

Save method has 2 parameters : a database with a default value (PrivateCloudDatabase) and an optional completion that returns the CKRecord. If the object already exists in iCloud, it will update instead of creating a new record.

// The Simplest Way
user.saveInCloud()

// With another Database. In this case, the public database
user.saveInCloud(CKContainer.default().publicCloudDatabase)

// With completion
user.saveInCloud { [weak self] (result: Result<CKRecord>) in
    guard let `self` = self else { return }
    switch result {
    case .success(_):
        print("\(user.username) saved in Cloud")
    case .failure(let error):
        print(error.localizedDescription)
    }
}

Retrieve

func retrieveFromCloud(_ database: CKDatabase = CKContainer.default().privateCloudDatabase, 
                       completion: @escaping ResultCompletion<[Self]>)

Retrieve method has 2 parameters : a database with a default value (PrivateCloudDatabase) and an optional completion that returns a [CodableCloud].

User.retrieveFromCloud(completion: { [weak self] (result: Result<[User]>) in
    guard let `self` = self else { return }
    switch result {
    case .success(let users):
        print("\(users.count) users retrieved from Cloud")
    case .failure(let error):
        print(error.localizedDescription)
    }
})

Remove

func removeFromCloud(_ database: CKDatabase = CKContainer.default().privateCloudDatabase,
                     _ completion: ResultCompletion<CKRecord.ID?>? = nil)

Retrieve method has 2 parameters : a database with a default value (PrivateCloudDatabase) and an optional completion that returns the CKRecord.ID as optional.

// The Simplest Way
user.removeFromCloud()

// With another Database. In this case, the public database
user.removeFromCloud(CKContainer.default().publicCloudDatabase)

// With completion
user.removeFromCloud { [weak self] (result: Result<CKRecord.ID?>) in
    guard let `self` = self else { return }
    switch result {
    case .success(_):
        print("\(user.username) removed from Cloud")
    case .failure(let error):
        print(error.localizedDescription)
    }
}

Contributing

Contributions are very welcome 🙌

License

CodableCloudKit
Copyright (c) 2019 CodableCloudKit [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
You might also like...
Simplified access to Apple's CloudKit
Simplified access to Apple's CloudKit

EVCloudKitDao Discuss EVCloudKitDao : What is this With Apple CloudKit, you can focus on your client-side app development and let iCloud eliminate the

This is the BlurrMC social media platform for iOS hosted on Apple's CloudKit.

BlurrMC for iOS This is the BlurrMC social media platform for IOS! WOOOOOOO! On this version of the social media platform, you have the full featured

CoreDataCloudKitShare - Learn how to use Core Data CloudKit

Sharing Core Data Objects Between iCloud Users Implement the flow to share data

Modern interface to UserDefaults + Codable support
Modern interface to UserDefaults + Codable support

Default Modern interface to UserDefaults + Codable support What is Default? Default is a library that extends what UserDefaults can do by providing ex

AppCodableStorage - Extends `@AppStorage` in SwiftUI to support any Codable object

AppCodableStorage Extends @AppStorage in SwiftUI to support any Codable object.

MoreCodable expands the possibilities of `Codable`.

MoreCodable MoreCodable expands the possibilities of "Codable". Installation Carthage github "tattn/MoreCodable" CocoaPods pod 'MoreCodable' Feature D

Typed key-value storage solution to store Codable types in various persistence layers with few lines of code!
Typed key-value storage solution to store Codable types in various persistence layers with few lines of code!

🗂 Stores A typed key-value storage solution to store Codable types in various persistence layers like User Defaults, File System, Core Data, Keychain

Save NSObject into NSUserDefaults in one-line, auto class mapping

Akaibu What is it ? Archive any class in just ONE-LINE of code. Automatically map class's properties under the hood. Drop in replacement of NSObject S

Listens to changes in a PostgreSQL Database and via websockets.

realtime-swift Listens to changes in a PostgreSQL Database and via websockets. A Swift client for Supabase Realtime server. Usage Creating a Socket co

Owner
Laurent Grondin
iOS Developer
Laurent Grondin
CodableFiles - Save and load Codable objects from DocumentDirectory on iOS Devices.

Welcome to CodableFiles, a simple library that provides an easier way to save, load or delete Codable objects in Documents directory. It’s primarily a

Egzon Pllana 36 Dec 20, 2022
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

Yalantis 252 Nov 4, 2022
Enables developers to write code that interacts with CloudKit in targets that don't support the CloudKit Framework directly

CloudKit Web Services This package enables developers to write code that interac

Eric Dorphy 3 May 11, 2022
Enables developers to write code that interacts with CloudKit in targets that don't support the CloudKit Framework directly

CloudKit Web Services This package enables developers to write code that interac

Eric Dorphy 2 Dec 27, 2021
Sync Realm Database with CloudKit

IceCream helps you sync Realm Database with CloudKit. It works like magic! Features Realm Database Off-line First Thread Safety Reactive Programming O

Soledad 1.8k Jan 6, 2023
Save-the-dot-project-swift - Save the dot project with swift

Save the Dot Apple introduced UIViewPropertyAnimator for iOS 10. We can use this

Kushal Shingote 2 Feb 8, 2022
Why not use UserDefaults to store Codable objects 😉

tl;dr You love Swift's Codable protocol and use it everywhere, who doesn't! Here is an easy and very light way to store and retrieve -reasonable amoun

Omar Albeik 452 Oct 17, 2022
A Generic CoreData Manager to accept any type of objects. Fastest way for adding a Database to your project.

QuickDB FileManager + CoreData ❗️ Save and Retrieve any thing in JUST ONE line of code ❗️ Fast usage dataBase to avoid struggling with dataBase comple

Behrad Kazemi 17 Sep 24, 2022
Effortlessly synchronize UserDefaults over iCloud.

Zephyr ??️ Effortlessly sync UserDefaults over iCloud About Zephyr synchronizes specific keys and/or all of your UserDefaults over iCloud using NSUbiq

Arthur Ariel Sabintsev 841 Dec 23, 2022
iForage helps foragers to track and manage foraging spots around them using CloudKit

iForage CloudKit Preface To expand on what I've created here: https://github.com/LynchConnor/iForage, I initially developed the app using Firebase. Th

Connor Lynch 3 Jul 14, 2022