Loading...
Searching...
No Matches
StorageManagerExample.swift
Go to the documentation of this file.
1import Foundation
2
3/**
4 * StorageManager and KeyValueStorage usage example for Swift
5 * Demonstrates working with storage management, key-value storage operations, and data persistence
6 */
7class StorageManagerExample {
8 private var sdk: NavigineSdk?
9 private var storageManager: StorageManager?
10 private var userStorage: KeyValueStorage?
11 private var appStorage: KeyValueStorage?
12 private var cacheStorage: KeyValueStorage?
13
14 init() {
15 initializeSdk()
16 setupStorages()
17 }
18
19 /**
20 * Initialize SDK and get StorageManager
21 */
22 private func initializeSdk() {
23 do {
24 // [swift_NavigineSdk_getInstance]
25 // Get SDK instance
26 sdk = NavigineSdk.getInstance()
27 // [swift_NavigineSdk_getInstance]
28
29 // [swift_NavigineSdk_setUserHash]
30 // Set user hash
31 sdk?.setUserHash("USER-HASH-HERE")
32 // [swift_NavigineSdk_setUserHash]
33
34 // [swift_NavigineSdk_setServer]
35 // Set server URL (optional)
36 sdk?.setServer("https://custom.navigine.com")
37 // [swift_NavigineSdk_setServer]
38
39 // [swift_NavigineSdk_getStorageManager]
40 // Get StorageManager for working with storages
41 storageManager = sdk?.getStorageManager()
42 // [swift_NavigineSdk_getStorageManager]
43
44 if storageManager != nil {
45 print("StorageManager successfully initialized")
46 }
47 } catch {
48 print("Error initializing SDK: \‍(error)")
49 }
50 }
51
52 /**
53 * Setup different storage instances
54 */
55 private func setupStorages() {
56 guard let storageManager = storageManager else {
57 print("StorageManager not initialized")
58 return
59 }
60
61 // [swift_StorageManager_getStorage]
62 // Get or create different storage instances
63 userStorage = storageManager.getStorage(name: "user_preferences")
64 appStorage = storageManager.getStorage(name: "app_settings")
65 cacheStorage = storageManager.getStorage(name: "cache")
66 // [swift_StorageManager_getStorage]
67
68 print("Storage instances created")
69 }
70
71 /**
72 * Demonstrate StorageManager methods
73 */
74 func demonstrateStorageManagerMethods() {
75 guard let storageManager = storageManager else {
76 print("StorageManager not initialized")
77 return
78 }
79
80 // [swift_StorageManager_getStorageList]
81 // Get list of all existing storages
82 let storageList: [String] = storageManager.getStorageList()
83 print("Existing storages: \‍(storageList)")
84 // [swift_StorageManager_getStorageList]
85
86 // [swift_StorageManager_getStorage1]
87 // Get or create storage by name
88 let testStorage: KeyValueStorage = storageManager.getStorage(name: "test_storage")
89 print("Created test storage")
90 // [swift_StorageManager_getStorage1]
91
92 // Demonstrate storage creation and listing
93 storageManager.getStorage(name: "another_storage")
94 let updatedList: [String] = storageManager.getStorageList()
95 print("Updated storage list: \‍(updatedList)")
96
97 // [swift_StorageManager_removeStorage]
98 // Remove storage and all its data
99 storageManager.removeStorage(name: "test_storage")
100 print("Removed test storage")
101 // [swift_StorageManager_removeStorage]
102
103 let finalList: [String] = storageManager.getStorageList()
104 print("Final storage list: \‍(finalList)")
105 }
106
107 /**
108 * Demonstrate KeyValueStorage methods
109 */
110 func demonstrateKeyValueStorageMethods() {
111 guard let userStorage = userStorage else {
112 print("User storage not initialized")
113 return
114 }
115
116 print("\n=== KeyValueStorage Methods Demonstration ===")
117
118 // [swift_KeyValueStorage_putString]
119 // Store string values
120 userStorage.putString(key: "user_name", value: "John Doe")
121 userStorage.putString(key: "user_email", value: "john.doe@example.com")
122 print("Stored string values")
123 // [swift_KeyValueStorage_putString]
124
125 // [swift_KeyValueStorage_putInt]
126 // Store integer values
127 userStorage.putInt(key: "user_age", value: 25)
128 userStorage.putInt(key: "login_count", value: 42)
129 print("Stored integer values")
130 // [swift_KeyValueStorage_putInt]
131
132 // [swift_KeyValueStorage_putLong]
133 // Store long values
134 userStorage.putLong(key: "registration_timestamp", value: 1640995200000)
135 userStorage.putLong(key: "last_login_timestamp", value: Int64(Date().timeIntervalSince1970 * 1000))
136 print("Stored long values")
137 // [swift_KeyValueStorage_putLong]
138
139 // [swift_KeyValueStorage_putBool]
140 // Store boolean values
141 userStorage.putBool(key: "is_premium", value: true)
142 userStorage.putBool(key: "notifications_enabled", value: false)
143 print("Stored boolean values")
144 // [swift_KeyValueStorage_putBool]
145
146 // [swift_KeyValueStorage_putFloat]
147 // Store float values
148 userStorage.putFloat(key: "user_rating", value: 4.5)
149 userStorage.putFloat(key: "temperature", value: 23.5)
150 print("Stored float values")
151 // [swift_KeyValueStorage_putFloat]
152
153 // [swift_KeyValueStorage_putDouble]
154 // Store double values
155 userStorage.putDouble(key: "user_location_lat", value: 55.7558)
156 userStorage.putDouble(key: "user_location_lng", value: 37.6176)
157 print("Stored double values")
158 // [swift_KeyValueStorage_putDouble]
159
160 // [swift_KeyValueStorage_contains]
161 // Check if keys exist
162 let hasUserName: Bool = userStorage.contains(key: "user_name")
163 let hasNonExistent: Bool = userStorage.contains(key: "non_existent_key")
164 print("Contains 'user_name': \‍(hasUserName)")
165 print("Contains 'non_existent_key': \‍(hasNonExistent)")
166 // [swift_KeyValueStorage_contains]
167
168 // [swift_KeyValueStorage_getKeys]
169 // Get all stored keys
170 let allKeys: [String] = userStorage.getKeys()
171 print("All stored keys: \‍(allKeys)")
172 // [swift_KeyValueStorage_getKeys]
173
174 // [swift_KeyValueStorage_getString]
175 // Retrieve string values with defaults
176 let userName: String = userStorage.getString(key: "user_name", defaultValue: "Unknown")
177 let userEmail: String = userStorage.getString(key: "user_email", defaultValue: "")
178 let nonExistent: String = userStorage.getString(key: "non_existent_key", defaultValue: "default_value")
179 print("User name: \‍(userName)")
180 print("User email: \‍(userEmail)")
181 print("Non-existent key: \‍(nonExistent)")
182 // [swift_KeyValueStorage_getString]
183
184 // [swift_KeyValueStorage_getInt]
185 // Retrieve integer values with defaults
186 let userAge: Int32 = userStorage.getInt(key: "user_age", defaultValue: 0)
187 let loginCount: Int32 = userStorage.getInt(key: "login_count", defaultValue: 0)
188 let nonExistentInt: Int32 = userStorage.getInt(key: "non_existent_int", defaultValue: -1)
189 print("User age: \‍(userAge)")
190 print("Login count: \‍(loginCount)")
191 print("Non-existent int: \‍(nonExistentInt)")
192 // [swift_KeyValueStorage_getInt]
193
194 // [swift_KeyValueStorage_getLong]
195 // Retrieve long values with defaults
196 let regTimestamp: Int64 = userStorage.getLong(key: "registration_timestamp", defaultValue: 0)
197 let lastLogin: Int64 = userStorage.getLong(key: "last_login_timestamp", defaultValue: 0)
198 let nonExistentLong: Int64 = userStorage.getLong(key: "non_existent_long", defaultValue: -1)
199 print("Registration timestamp: \‍(regTimestamp)")
200 print("Last login timestamp: \‍(lastLogin)")
201 print("Non-existent long: \‍(nonExistentLong)")
202 // [swift_KeyValueStorage_getLong]
203
204 // [swift_KeyValueStorage_getBool]
205 // Retrieve boolean values with defaults
206 let isPremium: Bool = userStorage.getBool(key: "is_premium", defaultValue: false)
207 let notificationsEnabled: Bool = userStorage.getBool(key: "notifications_enabled", defaultValue: true)
208 let nonExistentBool: Bool = userStorage.getBool(key: "non_existent_bool", defaultValue: false)
209 print("Is premium: \‍(isPremium)")
210 print("Notifications enabled: \‍(notificationsEnabled)")
211 print("Non-existent bool: \‍(nonExistentBool)")
212 // [swift_KeyValueStorage_getBool]
213
214 // [swift_KeyValueStorage_getFloat]
215 // Retrieve float values with defaults
216 let userRating: Float = userStorage.getFloat(key: "user_rating", defaultValue: 0.0)
217 let temperature: Float = userStorage.getFloat(key: "temperature", defaultValue: 0.0)
218 let nonExistentFloat: Float = userStorage.getFloat(key: "non_existent_float", defaultValue: -1.0)
219 print("User rating: \‍(userRating)")
220 print("Temperature: \‍(temperature)")
221 print("Non-existent float: \‍(nonExistentFloat)")
222 // [swift_KeyValueStorage_getFloat]
223
224 // [swift_KeyValueStorage_getDouble]
225 // Retrieve double values with defaults
226 let userLat: Double = userStorage.getDouble(key: "user_location_lat", defaultValue: 0.0)
227 let userLng: Double = userStorage.getDouble(key: "user_location_lng", defaultValue: 0.0)
228 let nonExistentDouble: Double = userStorage.getDouble(key: "non_existent_double", defaultValue: -1.0)
229 print("User location lat: \‍(userLat)")
230 print("User location lng: \‍(userLng)")
231 print("Non-existent double: \‍(nonExistentDouble)")
232 // [swift_KeyValueStorage_getDouble]
233
234 // [swift_KeyValueStorage_remove]
235 // Remove specific keys
236 userStorage.remove(key: "user_age")
237 userStorage.remove(key: "non_existent_key") // No-op
238 print("Removed 'user_age' key")
239 // [swift_KeyValueStorage_remove]
240
241 // Verify removal
242 let stillHasAge: Bool = userStorage.contains(key: "user_age")
243 print("Still contains 'user_age': \‍(stillHasAge)")
244
245 // [swift_KeyValueStorage_clear]
246 // Clear all data
247 userStorage.clear()
248 print("Cleared all data from user storage")
249 // [swift_KeyValueStorage_clear]
250
251 // Verify clear
252 let keysAfterClear: [String] = userStorage.getKeys()
253 print("Keys after clear: \‍(keysAfterClear)")
254 }
255
256 /**
257 * Demonstrate multiple storages
258 */
259 func demonstrateMultipleStorages() {
260 guard let userStorage = userStorage,
261 let appStorage = appStorage,
262 let cacheStorage = cacheStorage else {
263 print("Storages not initialized")
264 return
265 }
266
267 print("\n=== Multiple Storages Demonstration ===")
268
269 // Store different data in different storages
270 userStorage.putString(key: "name", value: "John Doe")
271 userStorage.putInt(key: "age", value: 25)
272 userStorage.putBool(key: "is_premium", value: true)
273
274 appStorage.putString(key: "theme", value: "dark")
275 appStorage.putInt(key: "api_version", value: 2)
276 appStorage.putBool(key: "debug_mode", value: false)
277
278 cacheStorage.putLong(key: "last_update", value: Int64(Date().timeIntervalSince1970 * 1000))
279 cacheStorage.putString(key: "api_token", value: "abc123")
280 cacheStorage.putDouble(key: "cached_rating", value: 4.2)
281
282 // Retrieve data from different storages
283 print("User storage data:")
284 demonstrateStorageData(storage: userStorage)
285
286 print("\nApp storage data:")
287 demonstrateStorageData(storage: appStorage)
288
289 print("\nCache storage data:")
290 demonstrateStorageData(storage: cacheStorage)
291 }
292
293 /**
294 * Demonstrate storage data
295 */
296 private func demonstrateStorageData(storage: KeyValueStorage) {
297 let keys: [String] = storage.getKeys()
298 for key in keys {
299 if storage.contains(key: key) {
300 // Try to get value as string first
301 let stringValue: String = storage.getString(key: key, defaultValue: "")
302 if !stringValue.isEmpty {
303 print(" \‍(key): \‍(stringValue) (string)")
304 continue
305 }
306
307 // Try integer
308 let intValue: Int32 = storage.getInt(key: key, defaultValue: -999999)
309 if intValue != -999999 {
310 print(" \‍(key): \‍(intValue) (int)")
311 continue
312 }
313
314 // Try long
315 let longValue: Int64 = storage.getLong(key: key, defaultValue: -999999)
316 if longValue != -999999 {
317 print(" \‍(key): \‍(longValue) (long)")
318 continue
319 }
320
321 // Try boolean
322 let boolValue: Bool = storage.getBool(key: key, defaultValue: false)
323 if storage.contains(key: key) {
324 print(" \‍(key): \‍(boolValue) (bool)")
325 continue
326 }
327
328 // Try float
329 let floatValue: Float = storage.getFloat(key: key, defaultValue: -999999.0)
330 if floatValue != -999999.0 {
331 print(" \‍(key): \‍(floatValue) (float)")
332 continue
333 }
334
335 // Try double
336 let doubleValue: Double = storage.getDouble(key: key, defaultValue: -999999.0)
337 if doubleValue != -999999.0 {
338 print(" \‍(key): \‍(doubleValue) (double)")
339 }
340 }
341 }
342 }
343
344 /**
345 * Demonstrate storage analytics
346 */
347 func demonstrateStorageAnalytics() {
348 guard let storageManager = storageManager else {
349 print("StorageManager not initialized")
350 return
351 }
352
353 print("\n=== Storage Analytics ===")
354
355 // Analyze all storages
356 let allStorages: [String] = storageManager.getStorageList()
357 print("Total storages: \‍(allStorages.count)")
358
359 for storageName in allStorages {
360 let storage: KeyValueStorage = storageManager.getStorage(name: storageName)
361 let keys: [String] = storage.getKeys()
362 print("Storage '\‍(storageName)' contains \‍(keys.count) items")
363
364 // Analyze data types
365 var stringCount = 0
366 var intCount = 0
367 var longCount = 0
368 var boolCount = 0
369 var floatCount = 0
370 var doubleCount = 0
371
372 for key in keys {
373 // Count by trying to get each type
374 let stringValue: String = storage.getString(key: key, defaultValue: "")
375 if !stringValue.isEmpty {
376 stringCount += 1
377 continue
378 }
379
380 let intValue: Int32 = storage.getInt(key: key, defaultValue: -999999)
381 if intValue != -999999 {
382 intCount += 1
383 continue
384 }
385
386 let longValue: Int64 = storage.getLong(key: key, defaultValue: -999999)
387 if longValue != -999999 {
388 longCount += 1
389 continue
390 }
391
392 let boolValue: Bool = storage.getBool(key: key, defaultValue: false)
393 if storage.contains(key: key) {
394 boolCount += 1
395 continue
396 }
397
398 let floatValue: Float = storage.getFloat(key: key, defaultValue: -999999.0)
399 if floatValue != -999999.0 {
400 floatCount += 1
401 continue
402 }
403
404 let doubleValue: Double = storage.getDouble(key: key, defaultValue: -999999.0)
405 if doubleValue != -999999.0 {
406 doubleCount += 1
407 }
408 }
409
410 print(" - Strings: \‍(stringCount)")
411 print(" - Integers: \‍(intCount)")
412 print(" - Longs: \‍(longCount)")
413 print(" - Booleans: \‍(boolCount)")
414 print(" - Floats: \‍(floatCount)")
415 print(" - Doubles: \‍(doubleCount)")
416 }
417 }
418
419 /**
420 * Demonstrate data migration
421 */
422 func demonstrateDataMigration() {
423 guard let storageManager = storageManager else {
424 print("StorageManager not initialized")
425 return
426 }
427
428 print("\n=== Data Migration Demonstration ===")
429
430 // Create old and new storages
431 let oldStorage: KeyValueStorage = storageManager.getStorage(name: "old_storage")
432 let newStorage: KeyValueStorage = storageManager.getStorage(name: "new_storage")
433
434 // Populate old storage with data
435 oldStorage.putString(key: "name", value: "John Doe")
436 oldStorage.putInt(key: "age", value: 25)
437 oldStorage.putBool(key: "is_premium", value: true)
438 oldStorage.putDouble(key: "rating", value: 4.5)
439
440 print("Old storage before migration:")
441 demonstrateStorageData(storage: oldStorage)
442
443 // Migrate data from old to new storage
444 let keys: [String] = oldStorage.getKeys()
445 for key in keys {
446 // Migrate string data
447 let stringValue: String = oldStorage.getString(key: key, defaultValue: "")
448 if !stringValue.isEmpty {
449 newStorage.putString(key: key, value: stringValue)
450 continue
451 }
452
453 // Migrate integer data
454 let intValue: Int32 = oldStorage.getInt(key: key, defaultValue: -999999)
455 if intValue != -999999 {
456 newStorage.putInt(key: key, value: intValue)
457 continue
458 }
459
460 // Migrate long data
461 let longValue: Int64 = oldStorage.getLong(key: key, defaultValue: -999999)
462 if longValue != -999999 {
463 newStorage.putLong(key: key, value: longValue)
464 continue
465 }
466
467 // Migrate boolean data
468 let boolValue: Bool = oldStorage.getBool(key: key, defaultValue: false)
469 if oldStorage.contains(key: key) {
470 newStorage.putBool(key: key, value: boolValue)
471 continue
472 }
473
474 // Migrate float data
475 let floatValue: Float = oldStorage.getFloat(key: key, defaultValue: -999999.0)
476 if floatValue != -999999.0 {
477 newStorage.putFloat(key: key, value: floatValue)
478 continue
479 }
480
481 // Migrate double data
482 let doubleValue: Double = oldStorage.getDouble(key: key, defaultValue: -999999.0)
483 if doubleValue != -999999.0 {
484 newStorage.putDouble(key: key, value: doubleValue)
485 }
486 }
487
488 print("\nNew storage after migration:")
489 demonstrateStorageData(storage: newStorage)
490
491 // Remove old storage
492 storageManager.removeStorage(name: "old_storage")
493 print("\nRemoved old storage")
494
495 // Verify migration
496 let finalStorages: [String] = storageManager.getStorageList()
497 print("Final storage list: \‍(finalStorages)")
498 }
499
500 /**
501 * Demonstrate storage cleanup
502 */
503 func demonstrateStorageCleanup() {
504 guard let storageManager = storageManager else {
505 print("StorageManager not initialized")
506 return
507 }
508
509 print("\n=== Storage Cleanup Demonstration ===")
510
511 // Create some temporary storages
512 storageManager.getStorage(name: "temp_cache_1")
513 storageManager.getStorage(name: "temp_cache_2")
514 storageManager.getStorage(name: "permanent_storage")
515
516 let beforeCleanup: [String] = storageManager.getStorageList()
517 print("Storages before cleanup: \‍(beforeCleanup)")
518
519 // Clean up temporary storages
520 let storages: [String] = storageManager.getStorageList()
521 for storageName in storages {
522 if storageName.hasPrefix("temp_") {
523 storageManager.removeStorage(name: storageName)
524 print("Removed temporary storage: \‍(storageName)")
525 }
526 }
527
528 let afterCleanup: [String] = storageManager.getStorageList()
529 print("Storages after cleanup: \‍(afterCleanup)")
530 }
531
532 /**
533 * Run all demonstrations
534 */
535 func runAllDemonstrations() {
536 print("=== StorageManager and KeyValueStorage Examples ===\n")
537
538 demonstrateStorageManagerMethods()
539 demonstrateKeyValueStorageMethods()
540 demonstrateMultipleStorages()
541 demonstrateStorageAnalytics()
542 demonstrateDataMigration()
543 demonstrateStorageCleanup()
544
545 print("\n=== All demonstrations completed ===")
546 }
547
548 /**
549 * Cleanup resources
550 */
551 func cleanup() {
552 guard let storageManager = storageManager else { return }
553
554 // Remove test storages
555 let storages: [String] = storageManager.getStorageList()
556 for storageName in storages {
557 if storageName.hasPrefix("test_") ||
558 storageName.hasPrefix("temp_") ||
559 storageName.hasPrefix("old_") ||
560 storageName.hasPrefix("new_") {
561 storageManager.removeStorage(name: storageName)
562 }
563 }
564 }
565}
566
567/**
568 * Main function to run the example
569 */
570func main() {
571 let example = StorageManagerExample()
572
573 // Run all demonstrations
574 example.runAllDemonstrations()
575
576 // Cleanup
577 example.cleanup()
578
579 print("Example completed successfully!")
580}
581
582// Run the example
583main()