Reputation: 2302
I am moving a map marker 1 metre every 0.1 seconds with the following code:
for index in 1 ... points.count - 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 * Double(index)) {
self.driverMarker.position = points[index]
self.driverMarker.map = self.mapView
}
}
If the distance of all the points is 3000 metres then I set setting 3000 asyncAfters and I am worried this is inefficient.
Is there a better way to do this?
Upvotes: 0
Views: 581
Reputation: 5695
From your requirements stated in the question and comments, I believe using DispatchSourceTimer
is better for this task. I provided a sample code for reference below.
var count = 0
var bgTimer: DispatchSourceTimer?
func translateMarker() {
if count == (points.count - 1) {
bgTimer?.cancel()
bgTimer = nil
return
}
self.driverMarker.position = points[index]
self.driverMarker.map = self.mapView
count += 1
}
override func viewDidLoad() {
super.viewDidLoad()
let queue:DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
bgTimer = DispatchSource.makeTimerSource(flags: [], queue: queue)
bgTimer?.scheduleRepeating(deadline: DispatchTime.now(), interval: 0.1)
bgTimer?.setEventHandler(handler: {
self.translateMarker()
})
bgTimer?.resume()
}
Please let me know if you are facing any issues in implementing this. Feel free to suggest edits to make this better :)
Upvotes: 1