【问题标题】:Store Users Coordinates from google maps into Firebase Database将谷歌地图中的用户坐标存储到 Firebase 数据库中
【发布时间】:2018-12-28 06:24:51
【问题描述】:

我已经使用谷歌热图有一段时间了,我正在尝试将用户的位置以及其他一些项目存储在 firebase 中,然后在谷歌地图上显示它们。我一直在研究这种方法,但由于某种原因,我输入的代码不会存储用户的位置,但会存储所有其他信息,例如工作图片、工作类别、工作简历和价格。我想知道是否有人可以帮助我更正我的代码以显示如何将用户位置存储到 Firebase。

 @objc func handlePost() {
    let fromId = Auth.auth().currentUser!.uid
    let timestamp = Int(Date().timeIntervalSince1970)
    guard let image = JobImageView.image, let category = JobCategory.text, let description = JobBio.text, let cost = price.text else {
        print("Error")
        return
    }
    guard let uid = Auth.auth().currentUser?.uid  else {
        return
    }
    let imageName = NSUUID().uuidString
    let storageRef = Storage.storage().reference().child("job_images").child("\(imageName).png")

    if let JobImageUrl = self.JobImageView.image, let  uploadData = JobImageUrl.jpegData(compressionQuality: 0.75) {
        storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

            if error != nil, metadata != nil {
                print(error ?? "")
                return

            }

            storageRef.downloadURL(completion: { (url, error) in
                if error != nil {
                    print(error!.localizedDescription)
                    return
                }

                if let JobImageUrl = url?.absoluteString {
//if i attempt to store the users location, the line below crashes with the error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
                       let myLocation = self.mapView.myLocation
                    let coords: [String: Double] = [
                        "lat": myLocation!.coordinate.latitude,
                        "long": myLocation!.coordinate.longitude
                    ]
                    let values = ["category": category, "description": description, "cost": cost, "JobImageUrl": JobImageUrl, "fromId": fromId, "timestamp": timestamp, "location": coords] as [String : Any]
                    self.registerUserIntoDatabseWithUID(uid: uid, values: values as [String : AnyObject])
                }
            })
        })
    }
   }


   private func registerUserIntoDatabseWithUID(uid: String, values: [String: AnyObject]) {
    let ref = Database.database().reference(fromURL: "https://odd-jobs-llc-f854a.firebaseio.com/")
    let usersReference = ref.child("JobPost").child(uid)
    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in

        if err != nil {
            print("err")
            return
        }

        self.dismiss(animated: true, completion: nil)
    })

}

【问题讨论】:

  • 如果在registerUserIntoDatabseWithUID 中打印values.coords,它会显示什么?
  • @FrankvanPuffelen “[String : AnyObject]”类型的值没有成员“coords”
  • 抱歉,应该是打印values.location
  • @FrankvanPuffelen 同样的错误..
  • 有趣。由于您在调用registerUserIntoDatabseWithUID 之前将location 添加到values 数组中,因此我希望它会打印您添加的值。你有没有做进一步的调查? (请记住,Stack Overflow 是一个非常低效的交互式调试器)

标签: ios firebase google-maps firebase-realtime-database heatmap


【解决方案1】:

这不是一个直接的答案,但可能会导致一个。

问题是您问题中发布的代码按预期工作。这就是我所做的。

首先,我想将问题隔离为 Swift 编码错误或 Firebase 编码错误。我插入了一些测试值,注释掉了 Firebase 代码,并在 registerUserIntoDatabseWithUID 中添加了几个打印语句,以查看打印的内容是否是预期的数据。输出完全符合预期,包括两个测试坐标 2.0 和 3.0

func testBuildingDataset() {
    let coords: [String: Double] = [
        "lat": 2.0,
        "long": 3.0
    ]
    let uid = "uid_0"
    let category = "some cat"
    let description = "some desc"
    let cost = "some cost"
    let JobImageUrl = "some jobImgUrl"
    let fromId = "some fromId"
    let timestamp = "some timestamp"

    let values = ["category": category, "description": description, "cost": cost, "JobImageUrl": JobImageUrl, "fromId": fromId, "timestamp": timestamp, "location": coords] as [String : Any]
    registerUserIntoDatabseWithUID(uid: uid, values: values as [String : AnyObject])
}

func registerUserIntoDatabseWithUID(uid: String, values: [String: AnyObject]) {
    print(uid)
    print(values)

结论是数据集(至少我提供的)是可靠的,并且 Swift 代码按预期工作。然后我取消注释 Firebase 更新功能并再次运行测试。

func registerUserIntoDatabseWithUID(uid: String, values: [String: AnyObject]) {
    let usersReference = self.ref.child("JobPost").child(uid)
    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
        if err != nil {
            print("err")
            return
        }
        //self.dismiss(animated: true, completion: nil)
    })
}

然后检查了我的 Firebase。写入的数据完全符合预期。

"JobPost" : {
    "uid_0" : {
      "JobImageUrl" : "some jobImgUrl",
      "category" : "some cat",
      "cost" : "some cost",
      "description" : "some desc",
      "fromId" : "some fromId",
      "location" : {
        "lat" : 2,
        "long" : 3
      },
      "timestamp" : "some timestamp"
    }
  },

这得出一个总体结论,即问题中的代码有效,而问题在于该代码之外。

这是关键

//如果我尝试存储用户位置,下面的行会崩溃 出现错误 //Thread 1: Fatal error: Unexpectedly found nil while 展开可选值

let myLocation = self.mapView.myLocation

所以问题是 mapView 为 nil 或 myLocation 为 nil

但是,该代码未包含在问题中,因此无法进一步调查。此外,可以通过以安全的方式使用您的选项来捕获该错误

guard let myMap = self.mapView else {
   print("the mapview was nil")
   return
}
//use myMap from here as as you know it's not nil

另外,如果 mapView 是一个 MKMapView,它没有 myLocation 属性,只有一个 userLocation 属性,所以它显然是一个自定义类,也应该包含在问题中。

希望对您有所帮助。

【讨论】:

  • 使用你的方法后,我发现location是nil。我有办法解决这个问题吗?我尝试了 guard let 方法,直到返回 nil 并且不会保存用户位置。
  • 我也在使用 GMSMapView 而不是 MkMapView
  • @zachwilcox 你可能误诊了这个问题。并不是 Firebase 不会保存您的位置;您告诉 Firebase 保存的位置数据为零(根据我的回答),因此问题与 Firebase 无关,与您的 mapView 对象直接相关。您应该在调用问题中的代码之前检查 mapView 对象的填充方式。也许发布一个单独的问题,其中包括如何填充 GMSMapView mapView 对象以查看问题所在 - 可能在调用问题中的代码之前它已经超出范围?
  • 是的,我意识到了!当我注释掉“让 myLocation = self.mapView.myLocation 并更改纬度和经度以保存数字时。问题在于 mapView 为零。我想我明白为什么会这样,但我不太确定如何解决它。之所以为 nil,是因为在这个特定的 viewController 中,没有地图。我有两个视图控制器,一个是 googlemapsview,另一个是后控制器。我在想我必须启动谷歌地图?
  • @zachwilcox 看起来你有一个类 var 属性代表 mapObject self.mapView 所以从最初创建地图数据的地方你可以将它传递到你的类中可以得到它的属性。您不需要将地图绑定到 this viewController,但数据必须来自某个地方,因此只需将其传入即可。
猜你喜欢
  • 2012-09-21
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多