如何在UITableView中从本地Realm数据库获取数据?
Got it, let’s walk through how to set up your app to automatically pull from your local Realm database when there’s no network—you’re already halfway there with the save code you shared!
First, we need a reliable way to check if the device is online or offline. For iOS 12+, NWPathMonitor is the go-to tool. Here’s a simple singleton to handle this:
import Network class NetworkMonitor { static let shared = NetworkMonitor() private let monitor = NWPathMonitor() private let queue = DispatchQueue(label: "NetworkStatusQueue") var isOnline: Bool = true private init() { monitor.pathUpdateHandler = { path in self.isOnline = path.status == .satisfied } monitor.start(queue: queue) } }
First, double-check your ModelData conforms to Realm’s Object protocol (with a primary key for proper updates):
import RealmSwift class ModelData: Object { // Replace with your actual properties @Persisted var id: String @Persisted var content: String override static func primaryKey() -> String? { return "id" // Critical for the `update` flag to work correctly } }
Then refine your save code to avoid force-unwrapping (never use try! in production—handle errors properly):
// Map your remote data to ModelData instances self.dataSource = data.map { ModelData(value: $0) } do { guard let realm = Global.APP_REALM else { print("Realm instance not initialized") return } try realm.write { // Use `.modified` instead of `true` for clearer intent realm.add(self.dataSource, update: .modified) } print("Successfully saved data to local Realm") } catch { print("Failed to save data to Realm: \(error.localizedDescription)") }
Now, update your data fetch flow to prioritize local Realm data when offline:
func loadData() { if NetworkMonitor.shared.isOnline { // Fetch from remote API first, then save to Realm fetchRemoteData { [weak self] remoteData in guard let self = self else { return } self.saveToRealm(data: remoteData) self.updateUI(with: remoteData) } } else { // Pull directly from local Realm when offline guard let realm = Global.APP_REALM else { return } // Convert Realm's Results to an array (or use Results directly for auto-updates) let localData = realm.objects(ModelData.self).map { $0 } self.updateUI(with: localData) print("Loaded offline data from local Realm") } } // Helper for your existing save logic private func saveToRealm(data: [YourRemoteDataType]) { self.dataSource = data.map { ModelData(value: $0) } // Reuse the polished save code from Step 2 here }
To make it even smarter, you can listen for network status changes and auto-sync when the device comes back online:
// Add this to your view/view model setup var networkObservation: NSKeyValueObservation? func setupNetworkObservation() { networkObservation = NetworkMonitor.shared.observe(\.isOnline) { [weak self] _, _ in if NetworkMonitor.shared.isOnline { self?.fetchRemoteData() // Auto-sync when back online } } }
内容的提问来源于stack exchange,提问作者user9447187

