Jimmy Hough Jr's Site

CoreStore

Being too hungry to remember how to do multithreaded CoreData contexts (and too lazy), I looked for a wrapper over an alternative, though Realm was tempting. Enter CoreStore. The large README may be daunting, but its pretty easy to use. Code below fixed my crash upon updating the sync time.

     func uploadTemps2() async  {
        
        if let unsyncedTemps:[Temperature] = try? dataController.coreStore.fetchAll(
            From<Temperature>()
                .where(\.uploadedOn == nil)
        ) {
            print("will sync \(unsyncedTemps)")
            let dataToSend = unsyncedTemps.map( {
                TemperatureData(id: $0.syncID,
                                time: $0.timestamp!,
                                label: $0.name!,
                                value: $0.degreesC)
            })
            
            let string = String(data: try! encoder.encode(dataToSend), encoding: .utf8)!
            let bd = Body(string)
            
            let req = Request {
                Header.ContentType(.json)
                Method(.post)
                Header.Authorization(.bearer(AccountManager.shared.loginResponse!.apiToken.value))
                Url(protocol: .https,
                    url: "\(Preferences.shared.serverHostAddress)/\(ServerManager.Routes.batchTemps.rawValue)")
                bd
                }
                .onError({ e in
                    print(e)
                })
                .onJson({ j in
                    
                    self.dataController.coreStore.perform { transaction in
                        unsyncedTemps.forEach { loc in
                            let updated = transaction.edit(loc)
                            updated?.uploadedOn = Date()
                            
                        }
                            
                    } completion: { res in
                        switch res {
                        case .success:
                            print("done")
                        case .failure(let e):
                            print(e)
                        }
                    }
                })
            
            req.call()
        }
        else {
            print("no temps to sync")
        }
    }
Tagged with: