2
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

ObjectMapperを使ってFirebaseのリストを扱う

リストを定義したオブジェクトの配列にしてcollectionviewとかに使いたいっすよねー
Firebaseのデータはswiftだと型チェックとかkeyがあるかとか確認がめんどくさい。
ObjectMapperを使うとその辺が少し楽になる。

それとFirebaseのデータをObjectMapperを用いてデータ構造を管理する方法を参考にしている。
これのリスト版という感じ。

Mapperを定義

import ObjectMapper

struct Hoge: Mappable {
    var id: String!
    var name: String!

    init?(map: Map) { }

    mutating func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
    }
}

extensionでMapperを拡張

import ObjectMapper
import FirebaseDatabase

extension Mapper {
    public func map(snapshot: DataSnapshot) -> N? {
        guard var value = snapshot.value as? [ String: AnyObject ] else { return nil }
        value["id"] = snapshot.key as AnyObject
        guard let object = Mapper<N>().map(JSON: value) else {
            return nil
        }
        return object
    }

    public func mapArray(snapshot: DataSnapshot) -> [N?] {
        return snapshot.children.allObjects.map({object in
            guard let snapshot = object as? DataSnapshot else {
                return nil
            }
            return Mapper<N>().map(snapshot: snapshot)
        })
    }
}

リストのデータを取得

ref.child("hoges").observeSingleEvent(of: DataEventType.value, with: { snapshot in
    print(Mapper<Hoge>().mapArray(snapshot: snapshot))
})

まーnullチェックとかは結局どっかでしないといけないけどねー

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
2
Help us understand the problem. What are the problem?