Using GeoFire queries in Swift does not give useful output

后端 未结 2 720
鱼传尺愫
鱼传尺愫 2021-01-20 02:45

I\'m pretty desperate right now because I\'m trying to use GeoFire on my Firebase Database to find nearby users. I\'m pretty much stuck for two days now. I searched Google a

相关标签:
2条回答
  • 2021-01-20 03:23

    When using Geofire, you have two lists of data:

    1. the list of objects, in your case users
    2. the list of locations for those objects, which is maintained and queries through Geofire

    The two lists are indeed meant to be separate. From the Geofire documentation (emphasis mine):

    Assume you are building an app to rate bars and you store all information for a bar, e.g. name, business hours and price range, at /bars/<bar-id>. Later, you want to add the possibility for users to search for bars in their vicinity. This is where GeoFire comes in.

    You can store the location for each bar using GeoFire, using the bar IDs as GeoFire keys. GeoFire then allows you to easily query which bar IDs (the keys) are nearby. To display any additional information about the bars, you can load the information for each bar returned by the query at /bars/<bar-id>.

    I highlighted the two most important bits for your questions:

    1. the items in the list of users and the list of their locations should use the same key (this is what Andrew also pointed out in his answer). By using the same key, you can easily look up the user for a location and vice versa.
    2. you will need to separately load the user for each key within your query.

    Andrew shows how to properly write the locations for each user. What is left then is to load the additional information about each user that is in range of the result. You'd do this in he .keyEntered handler:

    let usersRef = ref.child("users")
    
    let circleQuery = geoFire?.query(at: center, withRadius: 10)
    circleQuery?.observe(.keyEntered, with: { (key: String?, location: CLLocation?) in
    
         print("Key '\(key!)' entered the search are and is at location '\(location!)'")
         // Load the user for the key
         let userRef = usersRef.child(key)
         userRef.observeSingleEvent(FIRDataEventType.value, with: { (snapshot) in
             let userDict = snapshot.value as? [String : AnyObject] ?? [:]
             // ...
         })
    })
    
    0 讨论(0)
  • 2021-01-20 03:40

    Try writing the locations with GeoFire like this. You don't need to store them under that location key.

    let ref = FIRDatabase.database().reference()
    let geofireRef = ref.child("users_locations")
    let geoFire = GeoFire(firebaseRef: geofireRef)
    
    geoFire?.setLocation(myLocation, forKey: uid!)
    
    0 讨论(0)
提交回复
热议问题