Ios 如何将Firebase中的用户个人列表抓取到tableview

Ios 如何将Firebase中的用户个人列表抓取到tableview,ios,swift,firebase,firebase-realtime-database,Ios,Swift,Firebase,Firebase Realtime Database,我试图简单地将用户最喜欢的地图提取到tableview上。 我认为这是一件非常基本的事情,但结果却非常困难 这里的代码是我迄今为止管理的最好的代码,试图以某种方式引用(users id)和(yourmaps id)来获取特定信息 比如说。因为用户已经制作了1张他最喜欢的地图(id为(-LPY4xer-b21hwMi9sp))。我想查看root[“yourmap”]中的所有地图,只将他的地图获取到tableview中 Firebase "users" { "6g55cHXH4begwooHQv

我试图简单地将用户最喜欢的地图提取到tableview上。 我认为这是一件非常基本的事情,但结果却非常困难

这里的代码是我迄今为止管理的最好的代码,试图以某种方式引用(users id)和(yourmaps id)来获取特定信息

比如说。因为用户已经制作了1张他最喜欢的地图(id为(-LPY4xer-b21hwMi9sp))。我想查看root[“yourmap”]中的所有地图,只将他的地图获取到tableview中

Firebase

"users" {
  "6g55cHXH4begwooHQvO4EKNV3xm1" : {
    "photoURL" : "https://firebasestorage.googleap...",
    "username" : "lbarri",
    "yourmaps" : {
      "-LpY4XEER-b21hwMi9sp" : true
    }
  }
}


"yourmaps": {
  "-LpY4XEER-b21hwMi9sp" : {
    "author" : {
      "photoURL" : "https://firebasestorage.googleapis.com/v...",
      "uid" : "6g55cHXH4begwooHQvO4EKNV3xm1",
      "username" : "lbarri"
    },
    "mapmoderators" : {
      "6g55cHXH4begwooHQvO4EKNV3xm1" : true
    },
    "mapphotoURL" : "https://firebasestorage.googleapis...",
    "mapusername" : "Hello World"
  },
  "-LpYo_pQ8zIOGHHlNU1Q" : {
    "author" : {
      "photoURL" : "https://firebasestorage.googleapis.com/v...3",
      "uid" : "RLFK9xnvhccTu2hbNHq0v05J2A13",
      "username" : "lbarri"
    },
    "mapmoderators" : {
      "RLFK9xnvhccTu2hbNHq0v05J2A13" : true
    },
    "mapphotoURL" : "https://firebasestorage.googleapis.com/...",
    "mapusername" : "Dream"
  }
}
Swift

    func getCurrentUserMaps() {
        guard let userProfile = UserService.currentUserProfile else { return }
        let currentUserId = userProfile.uid

        let userRef = Database.database().reference().child("users").child(currentUserId)
        userRef.observeSingleEvent(of: .value, with: { (snapshot) in

            let root = snapshot.value as? NSDictionary

            if let mapsByUser = root!["yourmaps"] as? [String: Bool] {
                for (documentId, status) in mapsByUser {
                    if status {
                        // Document is true, check for the maps
                        self.fetchyourmaps(key: documentId, owner: currentUserId)
                    }
                }
            }
        }) { (error) in
            print(error.localizedDescription)
        }
    }
    func fetchyourmaps(key:String, owner:String) {
        let yourMapRef = Database.database().reference().child("yourmaps")
        yourMapRef.observeSingleEvent(of: .value, with: {snapshot in
            let user = snapshot.value as? NSDictionary

            if let mapsByUser = user!["mapmoderators"] as? [String: Bool] {
                for (userId, status) in mapsByUser {
                    if userId == owner && status == true {
                        print("Owner \(owner) manages this \(user)")

                        var tempYourMap = [YourMapProfile]()
                        for key in (snapshot.value as? NSDictionary)! {
                            let childSnapshot = key as? DataSnapshot
                            let dict = childSnapshot!.value as? [String:AnyObject]                           
                            let author = dict!["author"] as? [String:AnyObject]
                            let uid = author!["uid"] as? String      
                            let username = author!["username"] as? String
                            let photoURL = author!["photoURL"] as? String
                            let url = URL(string:photoURL!)
                            let mapusername = dict!["mapusername"] as? String

                            let mapphotoURL = dict!["mapphotoURL"] as? String
                            let mapurl = URL(string:mapphotoURL!)

                            let userProfile = UserProfile(uid: uid!, username: username!, photoURL: url!, mapPoints: mapPoints!)
                            let yourmapprofile = YourMapProfile(mapid: childSnapshot!.key as! String, mapauthor: userProfile, mapusername: mapusername!, mapphotoURL: mapurl!)

                            tempYourMap.append(yourmapprofile)

                        }
                        self.yourmaps = tempYourMap
                        self.tableView.reloadData()
                    }
                }
            }
        })
    }

print(“所有者\(所有者)管理此\(用户)”)
会将正确的地图打印到控制台上

在这一行之后,就是我不知道如何将信息打包到我的tableview中的时候


我在任何地方都搜索了有关如何在将一个根文件夹引用到另一个根文件夹时从Firebase检索数据的信息,但我找不到任何有用的信息。因此,任何链接/指南/教程等都将不胜感激,我很乐意从那里开始。至少你应该这样做吗

有几种方法可以做到这一点,但这里有两种:选项1是利用深度查询来获取用户最喜爱的地图。第二种方法是迭代用户地图,并一次提取每个地图

func iterateToGetFavoriteMaps() {
    let uid = "uid_0"
    let userRef = self.ref.child("users").child(uid)
    userRef.observeSingleEvent(of: .value, with: { snapshot in
        if let mapRefs = snapshot.childSnapshot(forPath: "favorite_maps").value as? [String: Any] {
            let mapKeys = mapRefs.keys //note mapKeys is a Dict so we can directly access the keys
            for key in mapKeys {
                let mapRef = self.ref.child("allMaps").child(key)
                mapRef.observeSingleEvent(of: .value, with: { mapSnapshot in
                    let name = mapSnapshot.childSnapshot(forPath: "mapUserName").value as? String ?? "No Name"
                    print(name)
                })
            }
        }
    })
}
备选案文1:

从这样的“贴图”节点开始

allMaps
   map_0
      favorite_of
         uid_0: true
         uid_3: true
      map_user_name: "Larry"
   map_1
      favorite_of
         uid_2: true
      map_user_name: "Moe"
   map_2
      favorite_of
         uid_0: true
      map_user_name: "Curly"
users
   uid_0
      name: "Frank"
      favorite_maps:
         map_0: true
         map_2: true
   uid_1
      name: "Leroy"
      favorite_maps:
         map_1: true
然后,进行一次深度查询,以获取uid_0的所有常用映射

func queryToGetMyFavoriteMaps() {
    let uid = "uid_0"
    let ref = self.ref.child("allMaps")
    let path = "favorite_of/" + uid
    let query = ref.queryOrdered(byChild: path).queryEqual(toValue: true)
    query.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children {
            print(child) //prints the map_0 & map_2 nodes since that's the favorite onces
        }
    })
}
选择2

更改allMaps节点,因为我们不会执行查询

allMaps
   map_0
      map_user_name: "Larry"
   map_1
      map_user_name: "Moe"
   map_2
      map_user_name: "Curly"
然后用户节点将是这样的

allMaps
   map_0
      favorite_of
         uid_0: true
         uid_3: true
      map_user_name: "Larry"
   map_1
      favorite_of
         uid_2: true
      map_user_name: "Moe"
   map_2
      favorite_of
         uid_0: true
      map_user_name: "Curly"
users
   uid_0
      name: "Frank"
      favorite_maps:
         map_0: true
         map_2: true
   uid_1
      name: "Leroy"
      favorite_maps:
         map_1: true
然后,代码读取uid_0最喜欢的映射节点,并从该快照中获取密钥,然后对它们进行迭代,一次读取一个映射节点

func iterateToGetFavoriteMaps() {
    let uid = "uid_0"
    let userRef = self.ref.child("users").child(uid)
    userRef.observeSingleEvent(of: .value, with: { snapshot in
        if let mapRefs = snapshot.childSnapshot(forPath: "favorite_maps").value as? [String: Any] {
            let mapKeys = mapRefs.keys //note mapKeys is a Dict so we can directly access the keys
            for key in mapKeys {
                let mapRef = self.ref.child("allMaps").child(key)
                mapRef.observeSingleEvent(of: .value, with: { mapSnapshot in
                    let name = mapSnapshot.childSnapshot(forPath: "mapUserName").value as? String ?? "No Name"
                    print(name)
                })
            }
        }
    })
}

那么,您正在从用户(“-lpy4xer-b21hwMi9sp”)获取地图id,然后尝试引用“yourmaps”,并尝试使用该标识符提取地图,并使用返回的字典创建某种类型的对象?如果是这样的话,那么这在什么情况下没有按预期执行?您应该能够在观察用户并获取
mapId
Database.Database().reference().child(“yourmaps”).child(mapId).observeSingleEvent(of:.value,with:{(snapshot)in}
我确实尝试过,但我似乎不知道如何将其转换到我的Tableview中。然后代码就可以正常工作,直到-->行输入(snapshot.value作为NSDictionary){我假设
yourMaps
是表视图的数据源?这是正确的。