Loading...
Searching...
No Matches
AsyncRouteManagerExample.swift
Go to the documentation of this file.
1import Foundation
2
3/**
4 * AsyncRouteManager usage example for Swift
5 * Demonstrates working with async route planning, session management, and navigation
6 */
7class AsyncRouteManagerExample: NSObject {
8 private var sdk: NCNavigineSdk?
9 private var locationManager: NCLocationManager?
10 private var navigationManager: NCNavigationManager?
11 private var asyncRouteManager: NCAsyncRouteManager?
12 private var currentSession: NCRouteSession?
13
14 override init() {
15 super.init()
16 initializeSdk()
17 setupAsyncRouteListener()
18 }
19
20 /**
21 * Initialize SDK and get managers
22 */
23 private func initializeSdk() {
24 do {
25 // [swift_NavigineSdk_getInstance]
26 // Get SDK instance
27 sdk = NCNavigineSdk.getInstance()
28 // [swift_NavigineSdk_getInstance]
29
30 // [swift_NavigineSdk_setUserHash]
31 // Set user hash
32 sdk?.setUserHash("USER-HASH-HERE")
33 // [swift_NavigineSdk_setUserHash]
34
35 // [swift_NavigineSdk_setServer]
36 // Set server URL (optional)
37 sdk?.setServer("https://custom.navigine.com")
38 // [swift_NavigineSdk_setServer]
39
40 // [swift_NavigineSdk_getLocationManager]
41 // Get LocationManager for working with locations
42 locationManager = sdk?.getLocationManager()
43 // [swift_NavigineSdk_getLocationManager]
44
45 // [swift_NavigineSdk_getNavigationManager]
46 // Get NavigationManager for working with navigation
47 navigationManager = sdk?.getNavigationManager(locationManager)
48 // [swift_NavigineSdk_getNavigationManager]
49
50 // [swift_NavigineSdk_getAsyncRouteManager]
51 // Get AsyncRouteManager for working with async routes
52 asyncRouteManager = sdk?.getAsyncRouteManager(locationManager, navigationManager: navigationManager)
53 // [swift_NavigineSdk_getAsyncRouteManager]
54
55 if let locationManager = locationManager,
56 let navigationManager = navigationManager,
57 let asyncRouteManager = asyncRouteManager {
58 print("LocationManager, NavigationManager and AsyncRouteManager successfully initialized")
59 }
60 } catch {
61 print("Error initializing SDK: \‍(error)")
62 }
63 }
64
65 /**
66 * Setup async route listener
67 */
68 private func setupAsyncRouteListener() {
69 // AsyncRouteListener is implemented via protocol extension
70 // No additional setup needed for Swift
71 }
72
73 /**
74 * Demonstrate AsyncRouteManager methods
75 */
76 func demonstrateAsyncRouteManagerMethods() {
77 guard let manager = asyncRouteManager else {
78 print("AsyncRouteManager not initialized")
79 return
80 }
81
82 // Create test destination point
83 let destinationPoint = NCPoint(x: 100.0, y: 100.0)
84 let destinationLocationPoint = NCLocationPoint(point: destinationPoint, locationId: 12345, sublocationId: 1)
85
86 // Create route options
87 let routeOptions = NCRouteOptions(smoothRadius: 2.0, maxProjectionDistance: 5.0, maxAdvance: 2.0)
88
89 // [swift_AsyncRouteManager_createRouteSession]
90 // Create route session with default graph tag
91 let session = manager.createRouteSession(destinationLocationPoint, routeOptions: routeOptions)
92 print("Created route session with default graph tag")
93 // [swift_AsyncRouteManager_createRouteSession]
94
95 // [swift_AsyncRouteManager_createRouteSessionWithTag]
96 // Create route session with specific graph tag
97 let sessionWithTag = manager.createRouteSession(withTag: destinationLocationPoint, routeOptions: routeOptions, tag: "main")
98 print("Created route session with 'main' graph tag")
99 // [swift_AsyncRouteManager_createRouteSessionWithTag]
100
101 // Store session for later use
102 currentSession = session
103
104 // Add listener to session
105 // [swift_RouteSession_addRouteListener]
106 // Add route listener to session
107 session?.addRouteListener(self)
108 // [swift_RouteSession_addRouteListener]
109 }
110
111 /**
112 * Demonstrate RoutePath usage
113 */
114 func demonstrateRoutePathUsage(_ routePath: NCRoutePath) {
115 guard let routePath = routePath else {
116 print("RoutePath is null")
117 return
118 }
119
120 // [swift_RoutePath_getLength]
121 // Get route length
122 let length = routePath.getLength()
123 print("Route length: \‍(length) meters")
124 // [swift_RoutePath_getLength]
125
126 // [swift_RoutePath_getWeight]
127 // Get total route weight
128 let weight = routePath.getWeight()
129 print("Route weight: \‍(weight)")
130 // [swift_RoutePath_getWeight]
131
132 // [swift_RoutePath_getNodes]
133 // Get route nodes
134 let nodes = routePath.getNodes()
135 print("Number of route nodes: \‍(nodes.count)")
136 for node in nodes.prefix(3) {
137 demonstrateRouteNodeUsage(node)
138 }
139 // [swift_RoutePath_getNodes]
140
141 // [swift_RoutePath_head]
142 // Get route head (first 10 meters)
143 if let head = routePath.head(10.0) {
144 print("Route head length: \‍(head.getLength()) meters")
145 }
146 // [swift_RoutePath_head]
147
148 // [swift_RoutePath_tail]
149 // Get route tail (remaining after 10 meters)
150 if let tail = routePath.tail(10.0) {
151 print("Route tail length: \‍(tail.getLength()) meters")
152 }
153 // [swift_RoutePath_tail]
154 }
155
156 func demonstrateRouteNodeUsage(_ node: NCRouteNode) {
157 // [swift_RouteNode_getPoint]
158 let point = node.getPoint()
159 demonstrateLocationPointUsage(point)
160 // [swift_RouteNode_getPoint]
161
162 // [swift_RouteNode_getWeight]
163 let weight = node.getWeight()
164 print("Node weight: \‍(weight)")
165 // [swift_RouteNode_getWeight]
166
167 // [swift_RouteNode_getDistance]
168 let distance = node.getDistance()
169 print("Node distance: \‍(distance) meters")
170 // [swift_RouteNode_getDistance]
171
172 // [swift_RouteNode_getEvents]
173 let events = node.getEvents()
174 for event in events {
175 demonstrateRouteEventUsage(event)
176 }
177 // [swift_RouteNode_getEvents]
178 }
179
180 /**
181 * Demonstrate RouteEvent usage
182 */
183 func demonstrateRouteEventUsage(_ event: NCRouteEvent) {
184 guard let event = event else {
185 print("RouteEvent is null")
186 return
187 }
188
189 // [swift_RouteEvent_getType]
190 // Get event type
191 let type = event.getType()
192 print("Event type: \‍(type)")
193 // [swift_RouteEvent_getType]
194
195 // [swift_RouteEvent_getTurnEvent]
196 if let turnEvent = event.getTurnEvent() {
197 demonstrateTurnEventUsage(turnEvent)
198 }
199 // [swift_RouteEvent_getTurnEvent]
200
201 // [swift_RouteEvent_getTransitionEntryEvent]
202 if let entryEvent = event.getTransitionEntryEvent() {
203 demonstrateTransitionEntryEventUsage(entryEvent)
204 }
205 // [swift_RouteEvent_getTransitionEntryEvent]
206
207 // [swift_RouteEvent_getTransitionExitEvent]
208 if let exitEvent = event.getTransitionExitEvent() {
209 demonstrateTransitionExitEventUsage(exitEvent)
210 }
211 // [swift_RouteEvent_getTransitionExitEvent]
212
213 // [swift_RouteEvent_getTargetReachedEvent]
214 if let targetEvent = event.getTargetReachedEvent() {
215 demonstrateTargetReachedEventUsage(targetEvent)
216 }
217 // [swift_RouteEvent_getTargetReachedEvent]
218 }
219
220 /**
221 * Demonstrate RouteEventType enum values
222 */
223 func demonstrateRouteEventTypes() {
224 // [swift_RouteEventType_values]
225 // Get all route event type values
226 let types: [NCRouteEventType] = [.turnEvent, .transitionEntryEvent, .transitionExitEvent, .targetReachedEvent]
227 print("Available route event types:")
228 for type in types {
229 print(" - \‍(type)")
230 }
231 // [swift_RouteEventType_values]
232 }
233
234 func demonstrateTurnTypes() {
235 // [swift_TurnType_values]
236 let types: [NCTurnType] = [.leftSlight, .leftNormal, .leftSharp, .rightSlight, .rightNormal, .rightSharp, .complete]
237 for type in types {
238 print(" - \‍(type)")
239 }
240 // [swift_TurnType_values]
241 }
242
243 func demonstrateTurnEventUsage(_ event: NCTurnEvent) {
244 // [swift_TurnEvent_getType]
245 let type = event.getType()
246 print("Turn type: \‍(type)")
247 // [swift_TurnEvent_getType]
248
249 // [swift_TurnEvent_getAngle]
250 let angle = event.getAngle()
251 print("Turn angle: \‍(angle)")
252 // [swift_TurnEvent_getAngle]
253 }
254
255 func demonstrateTransitionEntryEventUsage(_ event: NCTransitionEntryEvent) {
256 // [swift_TransitionEntryEvent_getFrom]
257 let from = event.getFrom()
258 print("Transition entry from: \‍(from)")
259 // [swift_TransitionEntryEvent_getFrom]
260
261 // [swift_TransitionEntryEvent_getTo]
262 let to = event.getTo()
263 print("Transition entry to: \‍(to)")
264 // [swift_TransitionEntryEvent_getTo]
265 }
266
267 func demonstrateTransitionExitEventUsage(_ event: NCTransitionExitEvent) {
268 // [swift_TransitionExitEvent_getFrom]
269 let from = event.getFrom()
270 print("Transition exit from: \‍(from)")
271 // [swift_TransitionExitEvent_getFrom]
272
273 // [swift_TransitionExitEvent_getTo]
274 let to = event.getTo()
275 print("Transition exit to: \‍(to)")
276 // [swift_TransitionExitEvent_getTo]
277 }
278
279 func demonstrateTargetReachedEventUsage(_ event: NCTargetReachedEvent) {
280 // [swift_TargetReachedEvent_getIndex]
281 let index = event.getIndex()
282 print("Reached target index: \‍(index)")
283 // [swift_TargetReachedEvent_getIndex]
284
285 // [swift_TargetReachedEvent_getPoint]
286 let point = event.getPoint()
287 demonstrateLocationPointUsage(point)
288 // [swift_TargetReachedEvent_getPoint]
289 }
290
291 /**
292 * Demonstrate LocationPoint usage
293 */
294 func demonstrateLocationPointUsage(_ locationPoint: NCLocationPoint) {
295 guard let locationPoint = locationPoint else {
296 print("LocationPoint is null")
297 return
298 }
299
300 // [swift_LocationPoint_getPoint]
301 // Get point coordinates
302 let point = locationPoint.getPoint()
303 print("Location point: (\‍(point.getX()), \‍(point.getY()))")
304 // [swift_LocationPoint_getPoint]
305
306 // [swift_LocationPoint_getLocationId]
307 // Get location ID
308 let locationId = locationPoint.getLocationId()
309 print("Location ID: \‍(locationId)")
310 // [swift_LocationPoint_getLocationId]
311
312 // [swift_LocationPoint_getSublocationId]
313 // Get sublocation ID
314 let sublocationId = locationPoint.getSublocationId()
315 print("Sublocation ID: \‍(sublocationId)")
316 // [swift_LocationPoint_getSublocationId]
317
318 // [swift_LocationPoint_constructor]
319 // Create new location point
320 let newPoint = NCPoint(x: 25.0, y: 35.0)
321 let newLocationPoint = NCLocationPoint(point: newPoint, locationId: 12345, sublocationId: 2)
322 print("Created new location point: \‍(newLocationPoint.getPoint().getX()), \‍(newLocationPoint.getPoint().getY())")
323 // [swift_LocationPoint_constructor]
324 }
325
326 /**
327 * Demonstrate Point usage
328 */
329 func demonstratePointUsage(_ point: NCPoint) {
330 guard let point = point else {
331 print("Point is null")
332 return
333 }
334
335 // [swift_Point_getX]
336 // Get X coordinate
337 let x = point.getX()
338 print("Point X: \‍(x)")
339 // [swift_Point_getX]
340
341 // [swift_Point_getY]
342 // Get Y coordinate
343 let y = point.getY()
344 print("Point Y: \‍(y)")
345 // [swift_Point_getY]
346
347 // [swift_Point_constructor]
348 // Create new point
349 let newPoint = NCPoint(x: 15.0, y: 25.0)
350 print("Created new point: (\‍(newPoint.getX()), \‍(newPoint.getY()))")
351 // [swift_Point_constructor]
352 }
353
354 /**
355 * Demonstrate RouteOptions usage
356 */
357 func demonstrateRouteOptions() {
358 print("=== Route Options ===")
359
360 // [swift_RouteOptions_constructor]
361 // Create route options with custom parameters
362 let routeOptions = NCRouteOptions(smoothRadius: 3.0, maxProjectionDistance: 7.0, maxAdvance: 2.5)
363 print("Created route options with smoothRadius: \‍(routeOptions.getSmoothRadius()), maxProjectionDistance: \‍(routeOptions.getMaxProjectionDistance()), maxAdvance: \‍(routeOptions.getMaxAdvance())")
364 // [swift_RouteOptions_constructor]
365
366 // Demonstrate different route options configurations
367 let optionsList = [
368 NCRouteOptions(smoothRadius: 0.0, maxProjectionDistance: 5.0, maxAdvance: 2.0), // No smoothing
369 NCRouteOptions(smoothRadius: 2.0, maxProjectionDistance: 10.0, maxAdvance: 1.0), // High smoothing, high projection distance
370 NCRouteOptions(smoothRadius: 1.0, maxProjectionDistance: 3.0, maxAdvance: 3.0), // Low smoothing, low projection distance
371 ]
372
373 for (index, options) in optionsList.enumerated() {
374 print("Options \‍(index + 1): smoothRadius=\‍(options.getSmoothRadius()), maxProjectionDistance=\‍(options.getMaxProjectionDistance()), maxAdvance=\‍(options.getMaxAdvance())")
375 }
376 }
377
378 /**
379 * Demonstrate advanced async routing features
380 */
381 func demonstrateAdvancedAsyncRoutingFeatures() {
382 print("=== Advanced Async Routing Features ===")
383
384 guard let manager = asyncRouteManager else {
385 return
386 }
387
388 // Create multiple destination points
389 let destinations = [
390 NCLocationPoint(point: NCPoint(x: 50.0, y: 50.0), locationId: 12345, sublocationId: 1),
391 NCLocationPoint(point: NCPoint(x: 100.0, y: 100.0), locationId: 12345, sublocationId: 1),
392 NCLocationPoint(point: NCPoint(x: 150.0, y: 150.0), locationId: 12345, sublocationId: 1)
393 ]
394
395 // Create different route options for each destination
396 let optionsList = [
397 NCRouteOptions(smoothRadius: 2.0, maxProjectionDistance: 5.0, maxAdvance: 2.0),
398 NCRouteOptions(smoothRadius: 3.0, maxProjectionDistance: 7.0, maxAdvance: 1.5),
399 NCRouteOptions(smoothRadius: 1.0, maxProjectionDistance: 3.0, maxAdvance: 2.5),
400 ]
401
402 // Create sessions for each destination
403 var sessions: [NCRouteSession] = []
404 for (index, destination) in destinations.enumerated() {
405 let session = manager.createRouteSession(destination, routeOptions: optionsList[index])
406 sessions.append(session!)
407 print("Created session \‍(index + 1) for destination: \‍(destination.getPoint().getX()), \‍(destination.getPoint().getY())")
408
409 session?.addRouteListener(self)
410
411 Thread.sleep(forTimeInterval: 1.0)
412 }
413
414 // Wait for route updates
415 Thread.sleep(forTimeInterval: 3.0)
416
417 // Cancel all sessions
418 for (index, session) in sessions.enumerated() {
419 // [swift_AsyncRouteManager_cancelRouteSession]
420 // Cancel route session
421 manager.cancelRouteSession(session)
422 print("Cancelled session \‍(index + 1)")
423 // [swift_AsyncRouteManager_cancelRouteSession]
424
425 Thread.sleep(forTimeInterval: 1.0)
426 }
427 }
428
429 /**
430 * Demonstrate RouteStatus enum usage
431 */
432 func demonstrateRouteStatusUsage() {
433 print("=== RouteStatus Enum Usage ===")
434
435 // [swift_RouteStatus_values]
436 // Demonstrate all RouteStatus values
437 print("Available RouteStatus values:")
438 let allStatuses: [NCRouteStatus] = [.missingGraph, .missingPosition, .missingRoute, .missingProjection, .newRoute]
439 for status in allStatuses {
440 print(" - \‍(status): \‍(status.rawValue)")
441 }
442
443 // Demonstrate status checking
444 let testStatus: NCRouteStatus = .newRoute
445 switch testStatus {
446 case .newRoute:
447 print("Router is ready for navigation")
448 case .missingGraph:
449 print("Router is missing the route graph")
450 case .missingPosition:
451 print("Router is missing the current position")
452 case .missingProjection:
453 print("Current position is off the route graph")
454 case .missingRoute:
455 print("Router unable to find the route to the destination point")
456 }
457 // [swift_RouteStatus_values]
458 }
459
460 /**
461 * Demonstrate route session management
462 */
463 func demonstrateRouteSessionManagement() {
464 print("=== Route Session Management ===")
465
466 guard let manager = asyncRouteManager else {
467 return
468 }
469
470 // Create test destination
471 let destinationPoint = NCPoint(x: 75.0, y: 75.0)
472 let destinationLocationPoint = NCLocationPoint(point: destinationPoint, locationId: 12345, sublocationId: 1)
473 let routeOptions = NCRouteOptions(smoothRadius: 2.0, maxProjectionDistance: 5.0, maxAdvance: 2.0)
474
475 // Create session with default tag
476 let defaultSession = manager.createRouteSession(destinationLocationPoint, routeOptions: routeOptions)
477 print("Created session with default tag")
478
479 // Create session with specific tag
480 let taggedSession = manager.createRouteSession(withTag: destinationLocationPoint, routeOptions: routeOptions, tag: "elevator")
481 print("Created session with 'elevator' tag")
482
483 // Add listeners to both sessions
484 defaultSession?.addRouteListener(self)
485 taggedSession?.addRouteListener(self)
486
487 // Simulate some time passing
488 DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
489 // Remove listeners
490 // [swift_RouteSession_removeRouteListener1]
491 // Remove route listener from session
492 defaultSession?.removeRouteListener(self)
493 taggedSession?.removeRouteListener(self)
494 print("Removed listeners from sessions")
495 // [swift_RouteSession_removeRouteListener1]
496
497 // Cancel sessions
498 manager.cancelRouteSession(defaultSession)
499 manager.cancelRouteSession(taggedSession)
500 print("Cancelled both sessions")
501 }
502 }
503
504 /**
505 * Clean up resources
506 */
507 func cleanup() {
508 if let session = currentSession {
509 // [swift_RouteSession_removeRouteListener]
510 // Remove route listener
511 session.removeRouteListener(self)
512 // [swift_RouteSession_removeRouteListener]
513 }
514
515 if let manager = asyncRouteManager, let session = currentSession {
516 // [swift_AsyncRouteManager_cancelRouteSession_1]
517 // Cancel route session
518 manager.cancelRouteSession(session)
519 // [swift_AsyncRouteManager_cancelRouteSession_1]
520 }
521 }
522
523 /**
524 * Main demonstration method
525 */
526 func runExample() {
527 print("=== AsyncRouteManager Example ===")
528
529 demonstrateAsyncRouteManagerMethods()
530 demonstrateRouteEventTypes()
531 demonstrateTurnTypes()
532 demonstrateRouteOptions()
533 demonstrateRouteStatusUsage()
534 demonstrateRouteSessionManagement()
535 demonstrateAdvancedAsyncRoutingFeatures()
536
537 // Wait a bit for route updates
538 Thread.sleep(forTimeInterval: 3.0)
539
540 cleanup()
541 print("=== Example completed ===")
542 }
543}
544
545// MARK: - NCAsyncRouteListener
546
547extension AsyncRouteManagerExample: NCAsyncRouteListener {
548 // [swift_AsyncRouteListener_onRouteChanged]
549 func onRouteChanged(_ status: NCRouteStatus, currentPath: NCRoutePath) {
550 print("Route changed with status: \‍(status)")
551 if status == .newRoute && currentPath != nil {
552 demonstrateRoutePathUsage(currentPath)
553 } else {
554 print("Route not ready, status: \‍(status)")
555 }
556 }
557 // [swift_AsyncRouteListener_onRouteChanged]
558
559 // [swift_AsyncRouteListener_onRouteAdvanced]
560 func onRouteAdvanced(_ distance: Float, point: NCLocationPoint) {
561 print("Route advanced: \‍(distance) meters")
562 demonstrateLocationPointUsage(point)
563 }
564 // [swift_AsyncRouteListener_onRouteAdvanced]
565}
566
567/**
568 * Function to run the example
569 */
570func main() {
571 let example = AsyncRouteManagerExample()
572 example.runExample()
573}
574
575// Run the example
576main()