• Stars
    star
    225
  • Rank 177,187 (Top 4 %)
  • Language
    Swift
  • License
    Other
  • Created about 8 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Firebase model framework Salada. Salada is the best Firebase framework.

Version Platform Downloads

Salada 🍐

Salad is a Model for Firebase database. It can handle Snapshot of Firebase easily.

Make a Model with Salada

  • You no longer need to create a server.
  • You no longer need to make a mock.
  • It operates in real time.
  • You can create a reactive UI.

Requirements ❗️

Installation

CocoaPods

  • Insert pod 'Salada' to your Podfile.
  • Run pod install.

Usage 👀

Model

Model of the definition is very simple. To inherit the Object.

class User: Object {

    dynamic var name: String?
    dynamic var age: Int = 0
    dynamic var gender: String?
    dynamic var groups: Set<String> = []
    dynamic var items: [String] = []
    dynamic var url: URL?
    dynamic var birth: Date?
    dynamic var thumbnail: File?
    dynamic var followers: Relation<User> = []
}

When you want to create a property that you want to ignore.

// Group
class Group: Object {
    dynamic var name: String?
    dynamic var users: Set<String> = []
}

Property

Property are four that can be specified in Salada.

Property Description
String Simple string.
Number(Int, UInt, Double ...) Simple number.
URL URL
Date date
Array<String> Array of strings.
Set <String> Array of strings. Set is used in relationships.
Reation<Object> Reference
[String: Any] Object
AnyObject Use encode, decode function.

⚠️ Bool, Int, Float, and Double are not supported optional types.

Save and Update

Do not forget to change the database rules.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}
// This rule is dangerous. Please change the rules according to the model

https://firebase.google.com/docs/database/security/

The new model is stored in the save() or save(completion: ((NSError?, FIRDatabaseReference) -> Void)?). It is updated automatically when you change the property Model that has already been saved.

let group: Group = Group()
group.name = "iOS Development Team"
group.save { (error, ref) in

    do {
        let user: User = User()
        user.name = "john appleseed"
        user.gender = "man"
        user.age = 22
        user.items = ["Book", "Pen"]
        user.groups.insert(ref.key)
        user.save({ (error, ref) in
            group.users.insert(ref.key) // It is updated automatically
        })
    }

    do {
        let user: User = User()
        user.name = "Marilyn Monroe"
        user.gender = "woman"
        user.age = 34
        user.items = ["Rip"]
        user.groups.insert(ref.key)
        user.save({ (error, ref) in
            group.users.insert(ref.key) // It is updated automatically
        })
    }

}

Retrieving Data

  • observeSingle(eventType: FIRDataEventType, block: ([Tsp]) -> Void)
  • observeSingle(id: String, eventType: FIRDataEventType, block: (Tsp) -> Void)
User.observeSingle(FIRDataEventType.Value) { (users) in
    users.forEach({ (user) in
        // do samething
        if let groupId: String = user.groups.first {
            Group.observeSingle(groupId, eventType: .Value, block: { (group) in
                // do samething
            })
        }
    })
}

Remove Data

if let groupId: String = user.groups.first {
    Group.observeSingle(groupId, eventType: .Value, block: { (group) in
        group.remove()
    })
}

Custom Property

class User: Salada.Object {

    override class var _version: String {
        return "v1"
    }

    dynamic var name: String?
    dynamic var age: Int = 0
    dynamic var gender: String?
    dynamic var groups: Set<String> = []
    dynamic var items: [String] = []
    dynamic var location: CLLocation?
    dynamic var url: URL?
    dynamic var birth: Date?
    dynamic var thumbnail: File?
    dynamic var cover: File?
    dynamic var type: UserType = .first

    var tempName: String?

    override var ignore: [String] {
        return ["tempName"]
    }

    override func encode(_ key: String, value: Any?) -> Any? {
        if key == "location" {
            if let location = self.location {
                return ["latitude": location.coordinate.latitude, "longitude": location.coordinate.longitude]
            }
        } else if key == "type" {
            return self.type.rawValue as AnyObject?
        }
        return nil
    }

    override func decode(_ key: String, value: Any?) -> Any? {
        if key == "location" {
            if let location: [String: Double] = value as? [String: Double] {
                self.location = CLLocation(latitude: location["latitude"]!, longitude: location["longitude"]!)
                return self.location
            }
        } else if key == "type" {
            if let type: Int = value as? Int {
                self.type = UserType(rawValue: type)!
                return self.type
            }
        }
        return nil
    }
}

Upload file

You can easily save the file if you use the File. File saves the File in FirebaseStorage.

Do not forget to change the storage rules.

let user: User = User()
let image: UIImage = UIImage(named: "Salada")!
let data: NSData = UIImagePNGRepresentation(image)!
let thumbnail: File = File(data: data, mimeType: .jpeg)
user.thumbnail = thumbnail
user.save({ (error, ref) in
    // do something
})
let image: UIImage = #imageLiteral(resourceName: "salada")
let data: Data = UIImageJPEGRepresentation(image, 1)!
let file: File = File(data: data, mimeType: .jpeg)
item.file = file
let task: FIRStorageUploadTask = item.file?.save(completion: { (metadata, error) in
    if let error = error {
        print(error)
        return
    }
})

Download file

Download of File is also available through the File.

guard let user: User = self.datasource?.objectAtIndex(indexPath.item) else { return }
user.thumbnail?.dataWithMaxSize(1 * 2000 * 2000, completion: { (data, error) in
    if let error: NSError = error {
        print(error)
        return
    }
    cell.imageView?.image = UIImage(data: data!)
    cell.setNeedsLayout()
})

FirebaseUI makes it even easier to access.

# Only pull in FirebaseUI Storage features
pod 'FirebaseUI/Storage', '~> 3.0'
User.observeSingle(friend, eventType: .value, block: { (user) in
    if let user: User = user as? User {
        if let ref: FIRStorageReference = user.thumbnail?.ref {
            cell.imageView.sd_setImage(with: ref, placeholderImage: #imageLiteral(resourceName: "account_placeholder"))
        }
    }
 })

Relationship

Please use Relation to create a relationship between models. It can be defined by inheriting Relation class.

class Follower: Relation<User> {
    override class var _name: String {
        return "follower"
    }
}
class User: Object {
    let followers: Follower = []
}

Data Source

See SaladBar.

For example

// ViewController Sample

var dataSource: DataSource<User>?

override func viewDidLoad() {
    super.viewDidLoad()
    
    let options: Options = Options()
    options.limit = 10
    options.sortDescirptors = [NSSortDescriptor(key: "age", ascending: false)]
    self.dataSource = DataSource(reference: User.databaseRef, options: options, block: { [weak self](changes) in
        guard let tableView: UITableView = self?.tableView else { return }
        
        switch changes {
        case .initial:
            tableView.reloadData()
        case .update(let deletions, let insertions, let modifications):
            tableView.beginUpdates()
            tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic)
            tableView.endUpdates()
        case .error(let error):
            print(error)
        }
    })
}
// TableViewDatasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.dataSource?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    configure(cell, atIndexPath: indexPath)
    return cell
}

func configure(_ cell: TableViewCell, atIndexPath indexPath: IndexPath) {
    cell.disposer = self.dataSource?.observeObject(at: indexPath.item, block: { (user) in
        cell.imageView?.contentMode = .scaleAspectFill
        cell.textLabel?.text = user?.name
    })
}

private func tableView(_ tableView: UITableView, didEndDisplaying cell: TableViewCell, forRowAt indexPath: IndexPath) {
    cell.disposer?.dispose()
}

func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        self.dataSource?.removeObject(at: indexPath.item, cascade: true, block: { (key, error) in
            if let error: Error = error {
                print(error)
            }
        })
    }
}

Observe

You can receive data changes through observation.
And easy to manage observation using Disposer.

class ViewController: UIViewController {
    private var disposer: Disposer<User>?

    override func viewDidLoad() {
        super.viewDidLoad()
        disposer = User.observe(userID, eventType: .value) { user in
             //...
        }
    }

    deinit {
        // ... auto remove observe internal disposer when it deinitialized.
        // or manually and clearly dispose
        // disposer?.dispose()
    }
}

Salada has Disposer, AnyDisposer and NoDisposer.
See details: Disposer.swift

Reference

  • Salada Firebase model framework.
  • Tong Tong is library for using ElasticSearch with Swift.
  • dressing Dressing provides the functionality of CloudFunctions to connect Firebase and ElasticSearch.

Contributing

We welcome any contributions. See the CONTRIBUTING file for how to get involved.

Saladaは日本製です。日本人のコントリビューター大歓迎🎉

More Repositories

1

Bleu

BLE (Bluetooth LE) for U🎁 Bleu is the best in the Bluetooth library.
Swift
489
star
2

Toolbar

Awesome autolayout Toolbar. Toolbar is a library for iOS. You can easily create chat InputBar.
Swift
456
star
3

Pring

Cloud Firestore model framework for iOS - Google
Swift
259
star
4

Sumo

Sumo is a library that prepares for fast upload for iOS. It is effective when uploading by selecting images continuously.
Swift
241
star
5

Ballcap-iOS

Firebase Cloud Firestore support library for iOS. 🧢
Swift
228
star
6

PaperKit

PaperKit is like Paper app of Facebook
Objective-C
155
star
7

pring.ts

Cloud Firestore model framework for TypeScript - Google
TypeScript
109
star
8

ballcap.ts

Cloud Firestore support library for admin. 🧢
TypeScript
107
star
9

Demae

TypeScript
77
star
10

Router

Router is a library that assists with SwiftUI view transitions.
Swift
74
star
11

AssemblyLine

AssemblyLine is a library for easily writing workflows.
Swift
40
star
12

Injectable

Dependency Injection for Swift
Ruby
31
star
13

Deck

Deck is a library that provides a UI to reproduce stacked cards for SwiftUI.
Swift
25
star
14

Muni

Chat with Cloud Firestore
Swift
23
star
15

TimeRangePicker

Swift
21
star
16

firestore-commerce

firestore-commerce is a framework that links Firestore and Stripe. By manipulating the Ballcap data model, you can sell immediately.
TypeScript
16
star
17

FirebaseAdmin

Firebase admin for Swift is a Swift package that provides a simple interface to interact with the Firebase admin SDK.
Swift
13
star
18

pring-admin.ts

Cloud Firestore model framework for TypeScript - Google
TypeScript
13
star
19

schedule.ts

TypeScript
9
star
20

SwiftWebUI-WASM-CFs

JavaScript
9
star
21

Messagestore

Swift
8
star
22

DocumentID

FirebaseFirestoreSwift's library for lightweight use of DocumentIDs in SwiftUI.
Swift
8
star
23

Flow

Swift
8
star
24

jp-zipcode

TypeScript
7
star
25

passkit.ts

Apple Pay, Wallet Development. passkit.ts is a library for issuing pass with typescript.
TypeScript
7
star
26

PickerGroup

Multi-picker for iOS and Mac available in SwiftUI
Swift
6
star
27

scenario

The scenario is the Cloud Functions support library. It is possible to clarify the dependency and limit the side effects.
TypeScript
6
star
28

tradable.ts

tradable.ts is a basic protocol to implement EC in Firebase.
TypeScript
5
star
29

Msg

Msg is a chat library based on FirebaseFirestore.
Swift
5
star
30

AdvancedTableViewSample

Advanced TableView Design Sample
Swift
5
star
31

OnTheKeyboard

Toolbar on the keyboard
Swift
5
star
32

CalendarUI

Swift
5
star
33

PaperKit-Camera

PaperKit + Camera is a super cool user interface that has integrated the camera to the UI of Paper.
Objective-C
5
star
34

StripeAPI

StripeAPI is a Framework that can handle Stripe type-safely.
Swift
4
star
35

FirestoreSwift

Swift
4
star
36

CameraUI

Swift
4
star
37

FirebaseAPI

Lightweight Cloud Firestore Client API using googleapis gRPC.
Swift
4
star
38

classy

classy provides getter / setter to typescript.
TypeScript
3
star
39

vue-pring-sample

Vue + Cloud Firestore +TypeScript
Vue
3
star
40

Antenna

A simple BLE sample code
Swift
3
star
41

Chart

Swift
3
star
42

SaladaSample

Salada sample code. Using Firebase Realtime Database
Swift
3
star
43

ReactionToolbar

ReactionToolbar is the UI, such as the Facebook of Ractions.
Swift
2
star
44

Tradable

Swift
2
star
45

flow.ts

Flow enables coding of structured scripts.
JavaScript
2
star
46

reaf

Host Next.js SSR app on Firebase Cloud Functions with Firebase Hosting redirects. Built with typescript.
TypeScript
2
star
47

ChatUI

Swift
2
star
48

MsgBox

MsgBox can build Chat by linking Firestore and Realm.
Swift
2
star
49

STPScrollView

STPScrollView is a Custom ScrollView
Objective-C
2
star
50

FirebaseInterface

Swift
2
star
51

tradestore.ts

TypeScript
2
star
52

RecurrenceRule

Swift
2
star
53

Socialbase

Socialbase is a framework for building SNS in Cloud Firestore.
Swift
2
star
54

STPPressGestureRecognizer

This is GestureRecognizer for iOS. It works like Force Touch.
Objective-C
2
star
55

ClockFace

Swift
2
star
56

ReactUI

JavaScript
2
star
57

FirebaseDemo

Firebase meetup #4
Ruby
2
star
58

Chat

Swift
1
star
59

MultiListener

Swift
1
star
60

FileSystemNavigator

Swift
1
star
61

SwiftUICell

SwiftUICell runs SwiftUI as CollectionView Cell
Swift
1
star
62

EventStack

Swift
1
star
63

Tong

Tong is library for using ElasticSearch with Swift.
Swift
1
star
64

Timeline

Swift
1
star
65

Calendar

Swift
1
star
66

Paym

Swift
1
star
67

document-propagator.ts

TypeScript
1
star
68

dressing

Dressing provides the functionality of CloudFunctions to connect Firebase and ElasticSearch. You need to use Salada for clients.
JavaScript
1
star
69

PHFetchedResultsController

A fetchedResultsController for PhotoKit. It can be divided into sections by date PhotoKit
Objective-C
1
star
70

NSMutableURLRequestMultipart

NSMutableURLRequestMultipart is a category of NSMutableURLRequest for sending a simple POST request.
Objective-C
1
star