调用addAnnotation时,UI Mapkit滞后

时间:2017-04-05 14:19:24

标签: swift multithreading mapkit mkannotation dispatch

我不明白为什么UI在1秒或2秒内没有响应(从数据库获取数据的时间),即使我使用DispatchQueue,也会每5秒发生一次。我使用UIMapKit作为地图,使用Firebase获取数据。

因此,在我的应用程序的viewDidLoad()中,我创建了一个计时器,每隔5秒执行一次函数sendMyLocation()。

timerLocationRequest = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(mapVC.sendMyLocation), userInfo: nil, repeats: true)

函数sendMylocation()调用函数addAnnotations(userArray: [User])。我使用dispatch_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数据库中获取数据(位置以及靠近我的用户的详细信息)。

 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
                })
            }
        })
    }
}

问题来自于在mapView上添加注释,因为当我在函数addAnnotations(userArray: [User])中对此行进行注释时,UI不会每5秒钟停止响应。 self.myMap.addAnnotations(self.userPinArray)

你有任何解决方案或者我做错了吗?

0 个答案:

没有答案