简体   繁体   中英

How to draw line point by point in Swift

I realised that I'm misusing the data retrived from the server in my tracker app. So I have this:

 @objc private func updateOnlineTrackWithNewData() {

    print("Tick")

    if let track = track {

        guard track.status == 1 else { return } // is track online?

        serverManager.tracks.updateOnlineTrack(for: track, success: { (trackNewPoints) in 
       //receive new data

            guard trackNewPoints.count > 1 else { return }

            for point in trackNewPoints {

                self.track?.points?.append(point)

                self.performSelector(onMainThread: #selector(self.updateOnlineTrackOnMap), with: nil, waitUntilDone: true)

            }

        }) { (error) in

            print(error ?? "Error updating online track")

           }
    }
}

Where trackNewPoints is basically an array of points that I'm appending to the main "track" and updateOnlineTrackOnMap is just printing it out. updateOnlineTrackWithNewData() function is triggered by timer, everything works correctly. But I want to draw line point by point to simulate realtime movement. How can I achieve that? performSelector doesn't seem to work.

Every 10 seconds I have 10 new points or so if that helps.

There is one way to do it. Create separate class Drawer

protocol Drawable { // add to your controller 
    func appendPoint(_ point: AnyObject)
    func updateOnlineTrackOnMap()
}

class Drawer {

    private var timer: Timer? = nil
    private var points: [AnyObject] = []

    func drawPoints(_ points: [AnyObject],
                    controller: Drawable) {
        self.points = points
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
            guard let point = self?.points.first else {
                timer.invalidate()
                return
            }
            DispatchQueue.global(qos: .userInteractive).async {
                controller.appendPoint(point)
                controller.updateOnlineTrackOnMap()
                self?.points.remove(at: 0)
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM