Swift 调用addAnnotation时UI Mapkit延迟
我不明白为什么用户界面在1秒或2秒(从数据库获取数据的时间)内没有响应,并且这种情况每5秒发生一次,即使我使用Swift 调用addAnnotation时UI Mapkit延迟,swift,multithreading,mapkit,mkannotation,dispatch,Swift,Multithreading,Mapkit,Mkannotation,Dispatch,我不明白为什么用户界面在1秒或2秒(从数据库获取数据的时间)内没有响应,并且这种情况每5秒发生一次,即使我使用DispatchQueue。我使用UIMapKit获取地图和Firebase数据 因此,在我的应用程序的viewdiload()中,我创建了一个计时器,每5秒执行一次函数sendMyLocation() timerLocationRequest = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selec
DispatchQueue
。我使用UIMapKit
获取地图和Firebase数据
因此,在我的应用程序的viewdiload()
中,我创建了一个计时器,每5秒执行一次函数sendMyLocation()
timerLocationRequest = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(mapVC.sendMyLocation), userInfo: nil, repeats: true)
函数sendMylocation()
调用函数addAnnotations(userArray:[User])
。我使用dispatch\u queue
在后台启动它
func sendMyLocation()
{
DispatchQueue.global(qos: .background).async {
self.addAnnotations(userArray: self.userArray)
}
}
函数addAnnotations从userArray添加注释
func addAnnotations(userArray: [User]) {
self.findNearbyUsers() // This function fill the userArray
// Here I create the annotations and at the end I add a tables of annotations to the mapView
for onePeople in userArray {
let oneUserPin = customPointAnnotation()
oneUserPin.coordinate.latitude = onePeople.latitude
oneUserPin.coordinate.longitude = onePeople.longitude
oneUserPin.imageName = onePeople.photo
oneUserPin.title = "\(onePeople.username)"
self.userPinArray.append(oneUserPin)
}
DispatchQueue.main.async {
self.myMap.addAnnotations(self.userPinArray) // I add annotations array to the mapView
}
}
最后,函数findNearbyUser()
从Firebase数据库获取数据(位置以及我附近用户的详细信息)
问题来自于在mapView
上添加注释,因为当我在函数addAnnotations(userArray:[User])
中注释这一行时,UI不会每5秒停止响应一次。
self.myMap.addAnnotations(self.userPinArray)
你有什么解决方案吗?或者我做错了什么吗?你有没有尝试在
findNearbyUsers
上放置一个完成处理程序,然后用它调用你的addAnnotations
函数?我进行了测试,但没有任何改变。。。无论如何谢谢你!
func findNearbyUsers() {
if let myLocation = self.manager.location {
let theGeoFire = GeoFire(firebaseRef: self.databaseRef.child("positions"))
let circleQuery = theGeoFire!.query(at: myLocation, withRadius: 0.3) //300 meters
var i=0
// Here I get keys of people near from me
_ = circleQuery!.observe(.keyEntered, with: { (key, location) in
if !self.nearbyUsers.contains(key!) && key != self.meUser.user_position_id {
self.nearbyUsers.append(key!)
let oneUser = User()
oneUser.user_id = key!
oneUser.latitude = (location?.coordinate.latitude)!
oneUser.longitude = (location?.coordinate.longitude)!
self.userArray.insert(oneUser, at: i)
i+=1
}
})
// Here I take details from users near from me
circleQuery?.observeReady({
for user in self.userArray {
self.databaseRef.child("users/\(user.user_id)").observe(.value, with: { snapshot in
let value = snapshot.value as? [String : AnyObject] ?? [:]
user.user_id = value["id_user"] as! String
user.photo = value["photoURL"] as! String
user.username = value["username"] as! String
})
}
})
}
}