UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Saving UserInfo to CoreData

Forums > watchOS

Hi I was wonder if anyone can help. I have watch app that does a check then passes two bit data to main app (a String and a Int). Then I want it to save them to CoreData. I have tried a few things. The Comment out code is want I need to save them to CoreData.

#if os(iOS)
// With This get *SwiftUI:0: Fatal error: No ObservableObject of type DataController found. A View.environmentObject(_:) for DataController may be missing as an ancestor of this view.*
@EnvironmentObject var dataController: DataController

// This does saved to CoreData but then crashes the iOS app!
//    @ObservedObject var dataController = DataController()

func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
    DispatchQueue.main.async {

    print("Data received \(userInfo)")
//            let viewContext = dataController.container.viewContext

    if let isDefect = userInfo["isDefect"] as? Bool {
        if isDefect {
// This is another data that save to different entity
            print("Defect")
//                let defect = Defect(context: viewContext)
        } else {
            print("Vehicle check")
//                let checkData = CheckData(context: viewContext)
//
            if let bonnet = userInfo["bonnet"] as? String {
//                    checkData.bonnet = bonnet
                print(bonnet)
            }
//
            if let numberDefect = userInfo["numberDefect"] as? Int {
//                    checkData.numberDefect = Int64(numberDefect)
                print("\(numberDefect)")
            }
//
//                checkData.dateCreated = Date()
        }
    }

//            dataController.save()
    }
}

// other Protocol methods that are required
#else
// watch Protocol method
#endif

5      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.