### Health Monitoring Setup Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of setting up and starting heartbeat monitoring with various health metrics. ```swift import DittoHeartbeat import DittoHealthMetrics import DittoDiskUsage import DittoPermissionsHealth let diskUsageVM = DiskUsageViewModel(ditto: ditto) let bluetoothMgr = BluetoothManager() let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, healthMetricProviders: [diskUsageVM, bluetoothMgr] ) let heartbeatVM = HeartbeatVM(ditto: ditto) heartbeatVM.startHeartbeat(config: config) { info in print("Heartbeat: \(info.presenceSnapshotDirectlyConnectedPeersCount) peers") } ``` -------------------------------- ### Importing All Tools Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of importing and using the AllToolsMenu module. ```swift import DittoAllToolsMenu import DittoSwift struct MainView: View { let ditto: Ditto var body: some View { AllToolsMenu(ditto: ditto) } } ``` -------------------------------- ### Ditto Instance Setup Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of initializing and activating a Ditto instance, either online or offline. ```swift import DittoSwift let ditto = Ditto() do { try ditto.activateOnlinePlayground(appID: "YOUR_APP_ID", token: "YOUR_TOKEN") // or try ditto.activateOfflinePlayground() } catch { print("Failed to activate Ditto: \(error)") } ``` -------------------------------- ### Programmatic Log Upload Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of programmatically initiating a log upload to the portal. ```swift // Programmatic log upload Task { do { try await LogUploader.uploadLogsToPortal(ditto: ditto) print("Log upload requested") } catch { print("Error: \(error)") } } ``` -------------------------------- ### Logging Management Setup (SwiftUI) Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of integrating LoggingDetailsView for logging management in a SwiftUI view. ```swift import DittoExportLogs import DittoSwift struct SettingsView: View { let ditto: Ditto var body: some View { LoggingDetailsView(ditto: ditto) } } ``` -------------------------------- ### Importing Individual Tools (SwiftUI) Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of importing and using the PresenceViewer module with SwiftUI. ```swift import DittoPresenceViewer import DittoSwift let presenceView = PresenceView(ditto: ditto) ``` -------------------------------- ### Importing Individual Tools (UIKit/AppKit) Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of importing and using the PresenceViewer module with UIKit/AppKit. ```swift // or for UIKit/AppKit let presenceView = DittoPresenceView(ditto: ditto) let vc = presenceView.viewController present(vc, animated: true) ``` -------------------------------- ### Runtime Log Level Control Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Examples of reading, changing, and saving the runtime log level. ```swift import DittoExportLogs import DittoSwift // Read current level let level = DittoLogger.minimumLogLevel // Change level DittoLogger.minimumLogLevel = .debug DittoLogger.minimumLogLevel.saveToStorage() // Enable/disable DittoLogger.isEnabled = true ``` -------------------------------- ### Mock configuration for Heartbeat testing Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of creating a mock configuration for testing Heartbeat without real health providers. ```swift let mockConfig = DittoHeartbeatConfig.mock // id: UUID(), interval: 10s, contains MockHealthMetricProvider ``` -------------------------------- ### Example Configuration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/heartbeat.md Example of how to configure the heartbeat. ```swift import DittoHeartbeat import DittoPermissionsHealth let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, metadata: [ "app_version": "1.0.0", "environment": "production" ], healthMetricProviders: [ BluetoothManager(), DiskUsageViewModel(ditto: ditto) ] ) ``` -------------------------------- ### Start Heartbeat and Access Data Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of starting the heartbeat and accessing the data via a callback. ```swift var heartBeatVm = HeartbeatVM(ditto: DittoManager.shared.ditto!) heartBeatVm.startHeartbeat(config: DittoHeartbeatConfig(secondsInterval: Int, metadata: metadata: [String:Any]? )) { heartbeatInfo in //use data } ``` -------------------------------- ### DittoPeersList Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usage of the PeersListView. ```swift PeersListView(ditto: ditto) ``` -------------------------------- ### DittoPresenceViewer Examples Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usages of the PresenceView and DittoPresenceView. ```swift PresenceView(ditto: ditto) // or let view = DittoPresenceView(ditto: ditto) let vc = view.viewController ``` -------------------------------- ### DittoAllToolsMenu Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usage of the AllToolsMenu view. ```swift AllToolsMenu(ditto: ditto) ``` -------------------------------- ### Pausing observation updates Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Example of how to pause observation updates for views like PeersList and PresenceDegradation when not needed. ```swift // PeersList and PresenceDegradation support pause vm.isPaused = true // Freezes observation ``` -------------------------------- ### Programmatic APIs Examples Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Examples demonstrating programmatic APIs for headless monitoring, including log export, log upload, and reading heartbeat data. ```swift // Export logs Task { let url = try await LogManager.shared.exportLogs() } // Upload logs to portal Task { try await LogUploader.uploadLogsToPortal(ditto: ditto) } // Read heartbeat data let vm = HeartbeatVM(ditto: ditto) vm.startHeartbeat(config: config) { info in print("Connected: \(info.presenceSnapshotDirectlyConnectedPeersCount)") } ``` -------------------------------- ### Disabling collection publishing for Heartbeat Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Configuration example to disable collection publishing for Heartbeat when it's not being queried, reducing disk I/O. ```swift let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, publishToDittoCollection: false // Skip Ditto write ) ``` -------------------------------- ### DittoDataBrowser Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usage of the DataBrowser view. ```swift DataBrowser(ditto: ditto) ``` -------------------------------- ### DittoExportLogs Examples Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usages of LoggingDetailsView and programmatic log upload. ```swift LoggingDetailsView(ditto: ditto) // Programmatic Task { try await LogUploader.uploadLogsToPortal(ditto: ditto) } ``` -------------------------------- ### DittoHeartbeat Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example of configuring and using the HeartbeatView and HeartbeatVM for periodic peer and health metric monitoring. ```swift let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10 ) HeartbeatView(ditto: ditto, config: config) // Programmatic let vm = HeartbeatVM(ditto: ditto) vm.startHeartbeat(config: config) { info in print("Peers: \(info.presenceSnapshotDirectlyConnectedPeersCount)") } ``` -------------------------------- ### SwiftUI Preview Support Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example of how to enable SwiftUI previews for a view. ```swift #if DEBUG struct HeartbeatView_Previews: PreviewProvider { static var previews: some View { HeartbeatView(ditto: Ditto(), config: nil) } } #endif ``` -------------------------------- ### SwiftUI Preview support Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Shows how to enable SwiftUI previews for views, conditional on DEBUG builds. ```swift #if DEBUG struct MyView_Previews: PreviewProvider { static var previews: some View { PresenceView(ditto: Ditto()) } } #endif ``` -------------------------------- ### Mock Configurations for Testing Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Provides an example of creating a mock configuration for testing purposes. ```swift static var mock: DittoHeartbeatConfig { DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, metadata: [...], healthMetricProviders: [MockHealthMetricProvider()] ) } ``` -------------------------------- ### BluetoothManager Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example usage of BluetoothManager as an ObservedObject. ```swift @ObservedObject var bluetoothManager = BluetoothManager() // Properties: authorizationStatusDescription, managerStateDescription ``` -------------------------------- ### NetworkManager Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example usage of NetworkManager as an ObservedObject. ```swift @ObservedObject var networkManager = NetworkManager() // Properties: isWifiEnabled ``` -------------------------------- ### SwiftUI Integration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/all-tools-menu.md Example of integrating AllToolsMenu into a SwiftUI view. ```swift import SwiftUI import DittoSwiftTools import DittoSwift struct ContentView: View { let ditto: Ditto var body: some View { AllToolsMenu(ditto: ditto) } } ``` -------------------------------- ### Real-Time Observation Examples Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Examples of how different views observe Ditto data sources and update in real-time. ```swift // PeersListView observes ditto.presence // Automatically updates when peers join/leave // DataBrowser observes ditto.store.collections // Automatically updates when collections are created/deleted // HeartbeatView observes __heartbeat collection // Automatically updates each interval ``` -------------------------------- ### DittoPresenceDegradation Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usage of the PresenceDegradationView. ```swift PresenceDegradationView(ditto: ditto) { expectedPeers, remotePeers, settings in print("Health: \(remotePeers?.count ?? 0) / \(expectedPeers)") } ``` -------------------------------- ### UIKit Usage for All Tools Menu Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of how to present the AllToolsMenu in UIKit by wrapping it in a UIHostingController. ```swift let vc = UIHostingController(rootView: AllToolsMenu(ditto: ditto)) navigationController?.pushViewController(vc, animated: true) ``` -------------------------------- ### Async/await for long-running operations Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Demonstrates the use of async/await for asynchronous tasks like exporting and uploading logs. ```swift Task { let logURL = try await LogManager.shared.exportLogs() } Task { try await LogUploader.uploadLogsToPortal(ditto: ditto) } ``` -------------------------------- ### Swift Package Manager Integration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Add DittoSwiftTools to your Swift Package Manager dependencies. ```swift dependencies: [ .package(url: "https://github.com/getditto/DittoSwiftTools", from: "1.0.0") ] ``` -------------------------------- ### Quick Start: Presence Monitoring Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Display the mesh topology using the PresenceView. ```swift import DittoPresenceViewer import DittoSwift struct MeshView: View { let ditto: Ditto var body: some View { PresenceView(ditto: ditto) } } ``` -------------------------------- ### Play/Pause Control Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example of implementing pause functionality to freeze observations in a view model. ```swift @Published var isPaused: Bool = false // In view model peersObserver = ditto.presence.observe { [weak self] graph in guard self?.isPaused == false else { return } // Update data } ``` -------------------------------- ### Document Format Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/DOCUMENTATION_INDEX.md All documents follow a consistent structure, including sections for Overview, Initialization, Usage, Features/Properties, and Feature-Specific Sections. ```markdown # Title ## Overview [What does this do?] ## Initialization [Constructor with signature and parameter table] ## Usage [Code examples for SwiftUI and UIKit] ## Features/Properties [Detailed explanation of features and behavior] ## [Feature-Specific Sections] [Details and examples] ``` -------------------------------- ### DittoPermissionsHealth Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example of using the PermissionsHealth view to display permission and connectivity status. ```swift PermissionsHealth() ``` -------------------------------- ### DittoExportData Examples Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usages of ExportData for iOS and macOS. ```swift ExportData(ditto: ditto) // macOS ExportData_macOS(ditto: ditto).export() ``` -------------------------------- ### DittoDiskUsage Examples Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example usages of DittoDiskUsageView and as a health metric provider. ```swift DittoDiskUsageView(ditto: ditto) // As health metric provider let vm = DiskUsageViewModel(ditto: ditto) let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, healthMetricProviders: [vm] ) ``` -------------------------------- ### Real-time observation in views Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Internal view logic demonstrating the use of Ditto observers for presence graph and store collection updates. ```swift // Internal to views: ditto.presence.observe { graph in ... } ditto.store.collections().observeLocal { ... } ``` -------------------------------- ### UIKit Integration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/all-tools-menu.md Example of presenting AllToolsMenu within a UIKit view controller. ```swift import UIKit import DittoSwiftTools import DittoSwift class ViewController: UIViewController { let ditto: Ditto func presentAllToolsMenu() { let hostingController = UIHostingController( rootView: AllToolsMenu(ditto: ditto) ) navigationController?.pushViewController(hostingController, animated: true) } } ``` -------------------------------- ### UIKit Usage for Presence Viewer Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of presenting the Presence Viewer in UIKit using a UIHostingController. ```swift func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { present(DittoPresenceView(ditto: DittoManager.shared.ditto).viewController, animated: true) { if let selected = tableView.indexPathForSelectedRow { tableView.deselectRow(at: selected, animated: true) } } } ``` -------------------------------- ### Health Metrics Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example of defining a custom HealthMetricProvider and configuring it with DittoHeartbeatConfig. ```swift struct CustomMetric: HealthMetricProvider { var metricName: String { "custom_metric" } func getCurrentState() -> HealthMetric { HealthMetric(isHealthy: true, details: ["status": "ok"]) } } let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, healthMetricProviders: [CustomMetric()] ) ``` -------------------------------- ### SwiftUI LoggingDetailsView as a Sheet Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of presenting the LoggingDetailsView as a modal sheet. ```swift .sheet(isPresented: $isPresented) { LoggingDetailsView() } ``` -------------------------------- ### UIKit Usage for Peers List Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of presenting the PeersListView in UIKit using a UIHostingController. ```swift let vc = UIHostingController(rootView: PeersListView(ditto: DittoManager.shared.ditto)) present(vc, animated: true) ``` -------------------------------- ### Error Handling: Throws Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example of an API that throws an error, specifically LogUploader.uploadLogsToPortal. ```swift try await LogUploader.uploadLogsToPortal(ditto: ditto) // throws DittoError ``` -------------------------------- ### SwiftUI Usage for Presence Viewer Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of using the PresenceView in SwiftUI to display the mesh graph. ```swift import DittoPresenceViewer struct PresenceViewer: View{ var body: some View { PresenceView(ditto: DittoManager.shared.ditto) } } ``` -------------------------------- ### SwiftUI LoggingDetailsView Integration Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of integrating the LoggingDetailsView into a SwiftUI view. ```swift import DittoExportLogs import DittoSwift import SwiftUI struct LoggingDetailsViewer: View { var body: some View { LoggingDetailsView(ditto: ) } } ``` -------------------------------- ### Error handling for Ditto operations Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Shows how to catch and handle DittoError during operations like uploading logs. ```swift do { try await LogUploader.uploadLogsToPortal(ditto: ditto) } catch { // Handle DittoError print("Database error: \(error)") } ``` -------------------------------- ### Heartbeat Tool Integration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/disk-usage.md Example of configuring the Heartbeat tool with DiskUsageViewModel. ```swift let diskUsageVM = DiskUsageViewModel(ditto: ditto) let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, healthMetricProviders: [diskUsageVM] ) ``` -------------------------------- ### Quick Start: All Tools in One View Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Integrate all DittoSwiftTools into a single view using the AllToolsMenu. ```swift import SwiftUI import DittoAllToolsMenu import DittoSwift struct ContentView: View { let ditto: Ditto var body: some View { AllToolsMenu(ditto: ditto) } } ``` -------------------------------- ### File operations error handling (debug) Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Illustrates how file operations might fail silently in production but trigger assertions in debug builds. ```swift // ExportData.swift assertionFailure("Ditto directory zipping failed.") ``` -------------------------------- ### UIKit Usage for Disk Usage Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of presenting the DittoDiskUsageView in UIKit using a UIHostingController. ```swift let vc = UIHostingController(rootView: DittoDiskUsageView(ditto: DittoManager.shared.ditto)) present(vc, animated: true) ``` -------------------------------- ### DittoHealthMetrics Custom Metric Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/module-reference.md Example of implementing the HealthMetricProvider protocol to create a custom health metric. ```swift struct CustomHealthMetric: HealthMetricProvider { var metricName: String { "custom" } func getCurrentState() -> HealthMetric { HealthMetric(isHealthy: true, details: ["status": "ok"]) } } ``` -------------------------------- ### UIKit Usage Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/presence-degradation.md Example of how to use PresenceDegradationView within a UIKit application by presenting it in a UIHostingController. ```swift import UIKit import DittoPresenceDegradation import DittoSwift let degradationView = PresenceDegradationView(ditto: ditto) { expectedPeers, remotePeers, settings in // Handle callback } let hostingController = UIHostingController(rootView: degradationView) present(hostingController, animated: true) ``` -------------------------------- ### Error Handling: Optional Returns Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example of an API that returns an optional, indicating potential failure by returning nil. ```swift func getCurrentState() -> HealthMetric? // nil if failed ``` -------------------------------- ### Background Threads Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates performing background work and updating the UI on the main thread. ```swift Task { let result = await backgroundWork() // Back on main for UI update self.uiState = result } ``` -------------------------------- ### UIKit Data Browser Integration Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of how to integrate the Data Browser into a UIKit application using UIHostingController. ```swift let vc = UIHostingController(rootView: DataBrowser(ditto: DittoManager.shared.ditto)) present(vc, animated: true) ``` -------------------------------- ### UIKit Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/disk-usage.md Example of how to use DittoDiskUsageView with UIKit. ```swift import UIKit import DittoDiskUsage import DittoSwift let diskUsageView = DittoDiskUsageView(ditto: ditto) let hostingController = UIHostingController(rootView: diskUsageView) present(hostingController, animated: true) ``` -------------------------------- ### SwiftUI Usage Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/presence-degradation.md Example of how to integrate PresenceDegradationView into a SwiftUI view to display mesh health status. ```swift import SwiftUI import DittoPresenceDegradation import DittoSwift struct MeshHealthScreen: View { let ditto: Ditto @State var meshStatus = "" var body: some View { PresenceDegradationView(ditto: ditto) { expectedPeers, remotePeers, settings in let connectedCount = remotePeers?.filter { $0.value.connected }.count ?? 0 meshStatus = connectedCount >= expectedPeers ? "Healthy" : "Degraded" } } } ``` -------------------------------- ### UIKit ExportLogs Integration Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of integrating ExportLogs into a UIKit application using UIHostingController. ```swift let vc = UIHostingController(rootView: ExportLogs()) present(vc, animated: true) ``` -------------------------------- ### Mock Configuration for Testing Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/heartbeat.md Example of creating a mock configuration for HeartbeatView for testing purposes. ```swift let mockConfig = DittoHeartbeatConfig.mock // Contains: 10-second interval, mock metadata, mock health metric provider ``` -------------------------------- ### UIKit Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/peers-list.md Example of how to use PeersListView with UIKit. ```swift import UIKit import DittoPeersList import DittoSwift let peersView = PeersListView(ditto: ditto) let hostingController = UIHostingController(rootView: peersView) present(hostingController, animated: true) ``` -------------------------------- ### SwiftUI ExportLogs Integration Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of using the ExportLogs view in SwiftUI, recommended to be called from within a sheet. ```swift .sheet(isPresented: $isPresented) { ExportLogs() } ``` -------------------------------- ### DQL Strict Mode Configuration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/configuration.md Configuration for enabling DQL Strict Mode, required for log export to the portal. ```bash // In your Ditto configuration // Set environment variable or config DQL_STRICT_MODE=false ``` -------------------------------- ### SwiftUI LoggingDetailsView as Navigation Title Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of embedding the LoggingDetailsView within a NavigationView. ```swift NavigationView { VStack { LoggingDetailsView() } .navigationTitle("Logging Settings") } ``` -------------------------------- ### SwiftUI Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/disk-usage.md Example of how to use DittoDiskUsageView within a SwiftUI view. ```swift import SwiftUI import DittoDiskUsage import DittoSwift struct DiskUsageScreen: View { let ditto: Ditto var body: some View { DittoDiskUsageView(ditto: ditto) } } ``` -------------------------------- ### SwiftUI Usage for Peers List Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of using the PeersListView in SwiftUI to display the list of local and connected remote peers. ```swift import DittoSwift struct PeersListViewer: View { var body: some View { PeersListView(ditto: DittoManager.shared.ditto) } } ``` -------------------------------- ### Quick Start: Heartbeat with Health Metrics Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Configure and display the HeartbeatView, including custom health metric providers like DiskUsageViewModel. ```swift import DittoHeartbeat import DittoDiskUsage import DittoSwift let diskVM = DiskUsageViewModel(ditto: ditto) let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10, metadata: ["app": "myapp"], healthMetricProviders: [diskVM] ) struct MonitorView: View { let ditto: Ditto var body: some View { HeartbeatView(ditto: ditto, config: config) } } ``` -------------------------------- ### SwiftUI Data Browser Integration Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of how to integrate the Data Browser into a SwiftUI view by passing a Ditto instance. ```swift import DittoDataBrowser struct DataBrowserView: View { var body: some View { DataBrowser(ditto: DittoManager.shared.ditto) } } ``` -------------------------------- ### SwiftUI Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/peers-list.md Example of how to use PeersListView within a SwiftUI view. ```swift import SwiftUI import DittoPeersList import DittoSwift struct PeersScreen: View { let ditto: Ditto var body: some View { PeersListView(ditto: ditto) } } ``` -------------------------------- ### LoggingDetailsView Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/export-logs.md Example of how to use LoggingDetailsView in a SwiftUI view. ```swift import SwiftUI import DittoExportLogs import DittoSwift struct LoggingScreen: View { let ditto: Ditto var body: some View { LoggingDetailsView(ditto: ditto) } } ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Instructions for adding DittoSwiftTools to your project using the Swift Package Manager. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/getditto/DittoSwiftTools", from: "1.0.0") ] ``` -------------------------------- ### LogUploader Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/export-logs.md Example of using the LogUploader to request log upload. ```swift import DittoExportLogs import DittoSwift Task { do { try await LogUploader.uploadLogsToPortal(ditto: ditto) print("Log upload requested successfully") } catch { print("Failed to request log upload: \(error)") } } ``` -------------------------------- ### HeartbeatVM Direct Callback Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/heartbeat.md Example demonstrating how to use HeartbeatVM with a direct callback for handling heartbeat information. ```swift var heartbeatVM = HeartbeatVM(ditto: ditto) heartbeatVM.startHeartbeat(config: config) { info in print("Connected peers: \(info.presenceSnapshotDirectlyConnectedPeersCount)") print("Health status: \(info.healthMetrics)") } ``` -------------------------------- ### SwiftUI Usage for Disk Usage Source: https://github.com/getditto/dittoswifttools/blob/main/README.md Example of using the DittoDiskUsageView in SwiftUI to display Ditto's file space usage. ```swift import DittoDiskUsage struct DiskUsageViewer: View { var body: some View { DittoDiskUsageView(ditto: DittoManager.shared.ditto) } } ``` -------------------------------- ### Async Export Operations Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Shows an example of an asynchronous function to export logs and how to call it within a Task. ```swift func getZippedLogs() async -> URL? { return try? await LogManager.shared.exportLogs() } Task { if let url = await getZippedLogs() { presentShareSheet(for: url) } } ``` -------------------------------- ### PresenceView SwiftUI Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/presence-viewer.md Example usage of PresenceView in a SwiftUI view. ```swift import SwiftUI import DittoPresenceViewer import DittoSwift struct PresenceViewerScreen: View { let ditto: Ditto var body: some View { PresenceView(ditto: ditto) } } ``` -------------------------------- ### Publisher for Reactive Subscribers Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example of a ViewModel exposing a publisher for reactive subscribers, using CurrentValueSubject and AnyPublisher. ```swift private var infoCurrentValueSubject = CurrentValueSubject(nil) public var infoPublisher: AnyPublisher { infoCurrentValueSubject.eraseToAnyPublisher() } // Emit updates infoCurrentValueSubject.send(hbInfo) ``` ```swift heartbeatVM.infoPublisher .compactMap { $0 } .sink { info in ... } .store(in: &cancellables) ``` -------------------------------- ### Cleanup on Disappear Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example of calling a cleanup method on a view model when the view disappears. ```swift .onDisappear { vm.cleanup() } ``` -------------------------------- ### Query Bar Example Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/data-browser.md Illustrates the input format for filtering documents using DQL legacy query syntax. ```text TextField: "title == \"Hello, World!\"" Button: "Enter" (macOS/tvOS) ``` -------------------------------- ### Publisher-Based Observation Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example of using a publisher to observe changes in a boolean property and trigger actions based on those changes. It also demonstrates storing the subscription in an AnyCancellable for proper memory management. ```swift private var cancellable = AnyCancellable({}) cancellable = $isPaused .sink { [weak self] paused in guard let self = self else { return } if paused { self.stopHeartbeat() } else { self.startHeartbeat() } } ``` -------------------------------- ### Upserting Data to Collections Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example of writing (upserting) data to a collection in the Ditto store. ```swift try ditto.store.collection(collectionName).upsert(doc) ``` -------------------------------- ### Xcodebuild Dependency Resolution Error Source: https://github.com/getditto/dittoswifttools/blob/main/README.md An example of an xcodebuild error related to Swift tools version mismatch during package dependency resolution. ```bash xcodebuild: error: Could not resolve package dependencies: package at 'http://github.com/getditto/DittoSwiftTools' @ 0ae82dcc1031d25ce5f6f20735b666312ecb2e53 is using Swift tools version 5.6.0 but the installed version is 5.5.0 in http://github.com/getditto/DittoSwiftTools ``` -------------------------------- ### HeartbeatVM Publisher Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/heartbeat.md Example demonstrating how to use HeartbeatVM with Combine publishers for handling heartbeat updates. ```swift var heartbeatVM = HeartbeatVM(ditto: ditto) heartbeatVM.infoPublisher .compactMap { $0 } .sink { info in // Handle heartbeat update } .store(in: &cancellables) heartbeatVM.startHeartbeat(config: config) { _ in } ``` -------------------------------- ### Error Handling: Assertions (Debug Only) Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example of using assertionFailure, which is only active in debug builds. ```swift assertionFailure("Export failed") // Debug mode only ``` -------------------------------- ### Optional Returns for Operations Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Shows examples of functions that return optional values, indicating potential absence of a result. ```swift func zipDittoDirectory() -> URL? func getCurrentState() -> HealthMetric? ``` -------------------------------- ### Silent Failures with try? Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Example of using 'try?' to handle operations that might fail silently, with an assertion failure for debugging. ```swift try? FileManager().removeItem(at: destinationURL) ``` ```swift assertionFailure("Ditto directory zipping failed.") ``` -------------------------------- ### Safe Main Thread Dispatch Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example demonstrating how to safely dispatch updates to the main thread from Ditto observers. ```swift // Safe main thread dispatch in observers DispatchQueue.main.async { self.uiData = newData } ``` -------------------------------- ### Architecture Observation Chain Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md This example demonstrates how a SwiftUI View observes ViewModel properties, which in turn observe Ditto's presence graph or collections. The ViewModel updates its @Published properties on the main thread, triggering automatic re-renders of the View. ```swift struct MyView: View { @StateObject var vm: PeersObserverVM init(ditto: Ditto) { self._vm = StateObject(wrappedValue: PeersObserverVM(ditto: ditto)) } var body: some View { List(vm.peers) { peer in Text(peer.deviceName) // Auto-updates when peers change } } } ``` -------------------------------- ### Reading Collections Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates how to read collections from the Ditto store. ```swift let collections = ditto.store.collections().exec() ``` -------------------------------- ### Initialization with StateObject Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Shows how to initialize view models using @StateObject for proper lifecycle management within SwiftUI views. ```swift @StateObject private var viewModel: DataBrowserViewModel @StateObject var vm: PresenceDegradationVM public init(ditto: Ditto) { self._viewModel = StateObject( wrappedValue: DataBrowserViewModel(ditto: ditto) ) } ``` -------------------------------- ### SwiftUI Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/permissions-health.md Example of how to use the PermissionsHealth view in SwiftUI. ```swift import SwiftUI import DittoPermissionsHealth struct PermissionsScreen: View { var body: some View { PermissionsHealth() } } ``` -------------------------------- ### HeartbeatScreen SwiftUI Integration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/heartbeat.md Example of integrating HeartbeatView into a SwiftUI screen. ```swift import SwiftUI import DittoHeartbeat import DittoSwift struct HeartbeatScreen: View { let ditto: Ditto let config = DittoHeartbeatConfig( id: UUID().uuidString, secondsInterval: 10 ) var body: some View { HeartbeatView(ditto: ditto, config: config) } } ``` -------------------------------- ### Type Aliases for Cross-Platform Code Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Illustrates using type aliases to write cross-platform compatible code. ```swift #if canImport(UIKit) public typealias PlatformView = UIView #elseif canImport(AppKit) public typealias PlatformView = NSView #endif ``` -------------------------------- ### ExportLogsToPortalView Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/export-logs.md Example of how to present ExportLogsToPortalView using a sheet. ```swift @State var showExportToPortal = false var body: some View { VStack { Button("Export Logs") { showExportToPortal = true } } .sheet(isPresented: $showExportToPortal) { ExportLogsToPortalView(ditto: ditto) { showExportToPortal = false } } } ``` -------------------------------- ### Throwable APIs for Error Handling Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Illustrates throwable APIs in Swift and how to handle potential errors using do-catch blocks. ```swift public static func uploadLogsToPortal(ditto: Ditto) async throws public func exportLogs() async throws -> URL ``` ```swift do { try await LogUploader.uploadLogsToPortal(ditto: ditto) } catch { // Handle DittoError } ``` -------------------------------- ### UIKit Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/permissions-health.md Example of how to present the PermissionsHealth view using UIHostingController in UIKit. ```swift import UIKit import DittoPermissionsHealth let permissionsView = PermissionsHealth() let hostingController = UIHostingController(rootView: permissionsView) present(hostingController, animated: true) ``` -------------------------------- ### Platform View Adapters with Conditional Compilation Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Shows how to use conditional compilation to adapt views for different platforms (iOS/macOS). ```swift #if os(iOS) private struct DittoPresenceViewRepresentable: UIViewRepresentable { ... } #elseif os(macOS) private struct DittoPresenceViewRepresentable: NSViewRepresentable { ... } #endif ``` -------------------------------- ### HeartbeatView UIKit Integration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/heartbeat.md Example of presenting HeartbeatView using UIHostingController for UIKit integration. ```swift let heartbeatView = HeartbeatView(ditto: ditto, config: config) let hostingController = UIHostingController(rootView: heartbeatView) present(hostingController, animated: true) ``` -------------------------------- ### DQL Queries for Filtering Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Illustrates how to use DQL (Ditto Query Language) to filter documents within a collection. ```swift let query = "SELECT * FROM \(collectionName) WHERE \(queryString)" let results = try ditto.store.exec(query: query) ``` -------------------------------- ### DittoPresenceView UIKit/AppKit Usage Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/presence-viewer.md Example usage of DittoPresenceView in a UIKit view controller. ```swift import UIKit import DittoPresenceViewer import DittoSwift class MeshViewController: UIViewController { let ditto: Ditto func showMeshGraph() { let presenceView = DittoPresenceView(ditto: ditto) present(presenceView.viewController, animated: true) } } ``` -------------------------------- ### AllToolsMenu Initializer Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/all-tools-menu.md Initializes the AllToolsMenu view with a Ditto instance. ```swift public struct AllToolsMenu: View { public init(ditto: Ditto?) } ``` -------------------------------- ### DittoDiskUsageView Initialization Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/disk-usage.md Initializes the DittoDiskUsageView with an active Ditto instance. ```swift public struct DittoDiskUsageView: View { public init(ditto: Ditto) } ``` -------------------------------- ### UIKit for Exporting Data Directory Source: https://github.com/getditto/dittoswifttools/blob/main/README.md This code snippet demonstrates how to present the `ExportData` view using a `UIHostingController` in UIKit. ```swift let vc = UIHostingController(rootView: ExportData(ditto: ditto)) present(vc, animated: true) ``` -------------------------------- ### LoggingDetailsView Initialization Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/export-logs.md Initializes the LoggingDetailsView with an active Ditto instance. ```swift public struct LoggingDetailsView: View { public init(ditto: Ditto) } ``` -------------------------------- ### UIKit for Presence Degradation Reporter Source: https://github.com/getditto/dittoswifttools/blob/main/README.md This code snippet demonstrates how to present the `PresenceDegradationView` using a `UIHostingController` in UIKit. ```swift let vc = UIHostingController(rootView: PresenceDegradationView(ditto: )) present(vc, animated: true) ``` -------------------------------- ### Heartbeat Configuration: Skip Write Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/README.md Example of configuring DittoHeartbeatConfig to skip writing to the Ditto collection. ```swift let config = DittoHeartbeatConfig( ... publishToDittoCollection: false // Skip write ) ``` -------------------------------- ### String-Based Configuration Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Shows how to use @Published properties for string-based configuration, including a computed property to convert the string to an integer. ```swift @Published var expectedPeers: String = "" @Published var sessionStartTime: String? var expectedPeersInt: Int { Int(expectedPeers) ?? 0 } ``` -------------------------------- ### Subscribing to Collections Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Shows how to subscribe to changes in collections within the Ditto store. ```swift subscription = ditto.store.collections().subscribe() ``` -------------------------------- ### UIKit for Exporting Logs to Portal Source: https://github.com/getditto/dittoswifttools/blob/main/README.md This code snippet demonstrates how to present the `ExportLogsToPortalView` using a `UIHostingController` in UIKit. ```swift let vc = UIHostingController( rootView: ExportLogsToPortalView(ditto: ditto) { // Dismiss logic self.dismiss(animated: true) } ) present(vc, animated: true) ``` -------------------------------- ### UIKit Heartbeat Presentation Source: https://github.com/getditto/dittoswifttools/blob/main/README.md How to present the HeartbeatView controller in a UIKit application. ```swift let vc = UIHostingController(rootView: HeartbeatView(ditto: , config: )) ``` -------------------------------- ### Conditional Compilation for Platform-Specific Code Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates using conditional compilation directives to include platform-specific code. ```swift #if os(iOS) ExportData_iOS(...) #elseif os(macOS) ExportData_macOS(...) #endif #if !os(tvOS) // Hide export on tvOS #endif ``` -------------------------------- ### Boolean Flags for State Management Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates using @Published properties for simple boolean state management, allowing for easy toggling in views. ```swift @Published var isPaused: Bool = false @Published var isEnabled: Bool = false @Published var apiEnabled: Bool = false ``` ```swift Button { vm.isPaused.toggle() } label: { Image(systemName: vm.isPaused ? "play.circle" : "pause.circle") } ``` -------------------------------- ### SwiftUI for Presence Degradation Reporter Source: https://github.com/getditto/dittoswifttools/blob/main/README.md This code snippet shows how to use the `PresenceDegradationView` in SwiftUI to monitor the mesh status. ```swift import DittoPresenceDegradation struct PresenceDegradationViewer: View { var body: some View { PresenceDegradationView(ditto: ) { expectedPeers, remotePeers, settings in //handle data } } } ``` -------------------------------- ### Enum-Based State Management Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates managing complex states using an enum with @Published properties. ```swift enum State: Equatable { case idle case exporting case success case error(String) } @Published var state: State = .idle ``` -------------------------------- ### Main Thread Updates Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates ensuring UI updates and state changes occur on the main thread using DispatchQueue.main.async. ```swift DispatchQueue.main.async { self.someData = ... } ``` -------------------------------- ### Async Ditto Store Operations Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md Demonstrates performing asynchronous operations on the Ditto store, including error handling. ```swift Task { do { try await LogUploader.uploadLogsToPortal(ditto: ditto) state = .success } catch { state = .error("Log export failed: \(error.localizedDescription)") } } ``` -------------------------------- ### ExportLogsToPortalView Initialization Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/export-logs.md Initializes the ExportLogsToPortalView with a Ditto instance and a dismiss callback. ```swift public struct ExportLogsToPortalView: View { public init(ditto: Ditto, onDismiss: @escaping () -> Void) } ``` -------------------------------- ### Standard View Model Structure Source: https://github.com/getditto/dittoswifttools/blob/main/_autodocs/view-models-and-patterns.md A typical MVVM view model structure using SwiftUI's ObservableObject protocol, demonstrating observation of Ditto's presence graph. ```swift @MainActor public class SomeViewModel: ObservableObject { @Published var someData: SomeType private var ditto: Ditto private var observer: DittoObserver? public init(ditto: Ditto) { self.ditto = ditto observeData() } private func observeData() { observer = ditto.presence.observe { graph in DispatchQueue.main.async { self.someData = ... } } } public func cleanup() { observer?.stop() } } ```