使用Swift的GeoFire

问题描述 投票:2回答:1

我打算使用GeoFire根据位置过滤我的firebase数据。不知道怎么开始这个,因为我刚刚开始开发。我有一个图片和一个标题等我在一个类中创建:

    @IBAction func shareDidTap(_ sender: Any) {
            if let image = image, let caption = textView.text {
                let newMedia = Media(type: "image", caption: caption, createdBy: user, image: image)
                    newMedia.save(completion: { (error) in
                        if let error = error {
                            self.alert(title: "Oops!", message: error.localizedDescription, buttonTitle: "OK")
                        } else {
                            self.user.share(newMedia: newMedia)

在一个单独的“用户”类(MVC)中,我将其保存到Firebase中

    func share(newMedia: Media) {
            DatabaseReference.users(uid: uid).reference().child("media").childByAutoId().setValue(newMedia.uid)
        }

我在哪里实例化GeoFire参考?我是否必须使用Core Location来获取我自己的Lat和Lon?任何帮助,将不胜感激。谢谢。

swift firebase geofire
1个回答
1
投票

添加GeoFire

用pods pod 'GeoFire', :git => 'https://github.com/firebase/geofire-objc.git'安装

然后导入项目import GeoFire

使用创建对它的引用

let rootRef = Database.database().reference()
let geoRef = GeoFire(firebaseRef: rootRef.child("user_locations"))

要获取当前用户位置,您可以通过cocoa pods使用位置管理器:https://github.com/varshylmobile/LocationManager

我猜你想要保存在数据库中的媒体有一个位置。然后使用GeoFire使用GeoFire.setlocation保存位置当您将帖子保存到数据库时调用此方法,GeoFire使用您的帖子ID处理添加位置的数据库结构。

一个例子:

geoFire!.setLocation(myLocation, forKey: userID) { (error) in
        if (error != nil) {
            debugPrint("An error occured: \(error)")
        } else {
            print("Saved location successfully!")
        }
    }

然后使用CircleQuery查询位置数据库您可以给出从给定位置(用户位置)查询数据库的距离的半径

一个例子:

let query = geoRef.query(at: userLocation, withRadius: 1000)

query?.observe(.keyEntered, with: { key, location in
    guard let key = key else { return }
    print("Key: " + key + "entered the search radius.")
})

我使用的一个非常好的教程是:https://www.youtube.com/watch?v=wr19iKENC-k&t=600s

查看他们的频道并查询GeoFire以获取可能对您有所帮助的其他视频。

© www.soinside.com 2019 - 2024. All rights reserved.