Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ObjectMapper + Firebase? #398

Closed
Dodig opened this issue Feb 25, 2016 · 11 comments
Closed

ObjectMapper + Firebase? #398

Dodig opened this issue Feb 25, 2016 · 11 comments

Comments

@Dodig
Copy link

Dodig commented Feb 25, 2016

Hi
How I can use ObjectMapper with Firebase?
Do you have any tutorials or samples?

@tristanhimmelman
Copy link
Owner

Sorry I have never used or heard of Firebase so I do not have any samples to tutorials for you.

@Dodig
Copy link
Author

Dodig commented Feb 28, 2016

@tristanhimmelman if you don't know Firebase you can check this: Firebase features 😉

Firebase Realtime Database
Data in your Firebase database is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our Android, iOS, and JavaScript SDKs, all of your clients share one Firebase database and automatically receive updates with the newest data.

With Firebase we manage NSDictionary and NSArray that I need to map to internal classes.
Can I use ObjectMapper for that?

@fractalzombie
Copy link

I'm interesting the same thing.

@TofPlay
Copy link

TofPlay commented Mar 7, 2016

Found it! 😀

Example with an Array of users

Json

Import this Json at https://<your db>.firebaseio.com/Users
Replace <your db> by your database

{
  "Users": [
    {
      "firstName": "Paul",
      "lastName": "Dumont"
    },
    {
      "firstName": "Jacque",
      "lastName": "Zero"
    },
    {
      "firstName": "Marc",
      "lastName": "Longshot"
    }
  ]
}

ObjectMapper class

import Foundation
import ObjectMapper

class User: Mappable {

  var firstName:String? = nil
  var lastName:String? = nil

  required init?(_ pMap: Map){
  }

  func mapping(pMap: Map) {
    self.firstName  <- pMap["firstName"]
    self.lastName   <- pMap["lastName"]
  }
}

View Controller

Replace <your db> by your database name

import UIKit
import Firebase
import ObjectMapper

class FirebaseViewController: UIViewController {

  override func viewDidLoad() {
      super.viewDidLoad()

      let lUsers = Firebase(url: "https://<your db>.firebaseio.com/Users")

      lUsers.observeEventType(.Value) {
        (pSnapshot:FDataSnapshot!) -> Void in

        if let lJsonArray = pSnapshot.value as? [[String : AnyObject]] {
          let lUsers = Mapper<User>().mapArray(lJsonArray)
          print("\(lUsers)")
        }
      }
   }
}

Debug view

image

@Dodig
Copy link
Author

Dodig commented Mar 7, 2016

Thanks 😄

@Dodig Dodig closed this as completed Mar 7, 2016
@omarzl
Copy link

omarzl commented Aug 9, 2016

Maybe this is helpful to someone, I ended up creating a mix of many resources on the Internet.
This is the base class:

`
import UIKit
import Firebase

class FIRDataObject: NSObject {

var snapshot: FIRDataSnapshot!
var key: String { return snapshot.key }
var ref: FIRDatabaseReference { return snapshot.ref }

required init(_ snapshot: FIRDataSnapshot) {
    super.init()
    self.snapshot = snapshot
    for child in snapshot.children {
        if respondsToSelector(Selector(child.key)) {
            setValue(child.value, forKey: child.key)
        }
    }
    load()
}

func load(){

    // retrieve the properties via the class_copyPropertyList function
    var count: UInt32 = 0;
    let myClass: AnyClass = self.classForCoder;
    let properties = class_copyPropertyList(myClass, &count)

    // iterate each objc_property_t struct
    for i:UInt32 in 0..<count{
        let property = properties[Int(i)]

        // retrieve the property name by calling property_getName function
        let cname = property_getName(property)

        // covert the c string into a Swift string
        if let name = String.fromCString(cname){
            if let value=snapshot.value!.valueForKey(name){
                self.setValue(value, forKey: name)
            }
        }
    }
    // release objc_property_t structs
    free(properties);
}

func save(){
    var dicc=[String:AnyObject]()

    // retrieve the properties via the class_copyPropertyList function
    var count: UInt32 = 0;
    let myClass: AnyClass = self.classForCoder;
    let properties = class_copyPropertyList(myClass, &count)

    // iterate each objc_property_t struct
    for i:UInt32 in 0..<count{
        let property = properties[Int(i)]

        // retrieve the property name by calling property_getName function
        let cname = property_getName(property)

        // covert the c string into a Swift string
        if let name = String.fromCString(cname){

            let value=self.valueForKey(name)
            dicc[name]=value
        }
    }
    ref.setValue(dicc)

    // release objc_property_t structs
    free(properties);
}

}
protocol FIRDatabaseReferenceable {
var ref: FIRDatabaseReference { get }
}
extension FIRDatabaseReferenceable {
var ref: FIRDatabaseReference {
return FIRDatabase.database().reference()
}
}
`

you only need to inherit from it:

`
class User: FIRDataObject {

var name=""
var username=""
var amigos=[String:Bool]()

}
`

and an example of use:

ref.child("users").child(user.uid).observeSingleEventOfType(.Value, withBlock: { (snapshot) in let user=User(snapshot) user.username="Demo" user.amigos[user.key]=true user.save() })

@callam
Copy link

callam commented Sep 19, 2016

@omarzl nice code you got there

@Jasonchan91
Copy link

nice sharing

@choioi
Copy link

choioi commented Apr 30, 2017

Very thanks !

@piv199
Copy link

piv199 commented Jul 12, 2017

@omarzl great way to deal with mapping

@Ankish
Copy link

Ankish commented Aug 2, 2017

Is there any way we can convert firebase snapshot object to raw json ? Then it could be easy to convert to this. Anythoughts ? Would like to if anyone has searlized snapshot object to JSON and using the mapper - are there any underlying implications of it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants