【发布时间】:2016-06-02 10:19:25
【问题描述】:
我在我的 iOS (Swift) 应用中使用新的 Google Firebase 数据库。
当用户创建一个帐户时,他会被添加到数据库中,其中包含一些参数,例如他的姓名、年龄,主要是他当前的位置(纬度/经度)。
我希望该应用能够找到他周围 XX 公里内的其他用户。
我这样创建了测试用户:
for index in 1...10 {
let profile: NSMutableDictionary = [
"username" : "User\(index)",
]
let parameters = [ // IT IS PARIS LOCATION
"latitude" : 48.856614,
"longitude" : 2.352222
]
self.ref.child("usersTest").child("userID:\(index)").child("profile").setValue(profile)
self.ref.child("usersTest").child("userID:\(index)").child("parameters").setValue(parameters)
}
我就是这样继续的:
// MARK: GET RANDOM USER
refHandle = ref.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
// IN THE DATABASE, I MODIFY THE USER 1 TO BE MY OWN ACCOUNT,
// SO I CHANGE THE LOCATION TO BE DIFFERENT FROM THE OTHER
// USERS LOCATION
let ownUserID = "userID:1"
let usersDict = snapshot.value!["usersTest"] as! NSDictionary
let ownLatitude = usersDict[ownUserID]!["parameters"]!!["latitude"] as! CLLocationDegrees
let ownLongitude = usersDict[ownUserID]!["parameters"]!!["longitude"] as! CLLocationDegrees
let ownMaxDistance = usersDict[ownUserID]!["parameters"]!!["max_distance"] as! CLLocationDegrees
self.myLocation = CLLocation(latitude: ownLatitude, longitude: ownLongitude)
let usersID = usersDict.allKeys as! [String]
for index in 0...usersID.count - 1 {
let foundUserID = usersID[index]
if foundUserID != ownUserID {
let users = usersDict[foundUserID] as! NSDictionary
self.usersArray["user\(index)"] = users
let userParameters = self.usersArray["user\(index)"]!["parameters"] as! NSDictionary
let latitude = userParameters["latitude"] as! CLLocationDegrees
let longitude = userParameters["longitude"] as! CLLocationDegrees
let userLocation = CLLocation(latitude: latitude, longitude: longitude)
let distance = self.getDistance(userLocation, city2: self.myLocation)
if distance < ownMaxDistance {
print("The user is inside your radius")
} else {
print("The user is outside your radius")
}
}
}
})
// MARK: GET DISTANCE - FUNCTION
func getDistance(city1: CLLocation, city2: CLLocation) -> CLLocationDegrees {
let distance: CLLocationDistance = (city1.distanceFromLocation(city2)) / 1000
return distance
}
这种方式的问题是所有数据库都被加载了,因为应用程序加载了数据库,然后它检查找到的用户是在你的半径之内还是之外(ownMaxDistance)。
我不知道如何根据找到的用户与用户之间的距离,按升序对找到的用户进行分类。
数据库中有100/200个用户是没有问题的,但是如果数据库有几千个用户,加载所有用户会很长!
感谢您的帮助!
更新 1
明确地说,它是一个类似于 Tinder 的应用程序
【问题讨论】:
标签: database swift firebase location cllocation