I am a new swifter from objective-c.
In the code:
Here is no 'WKHostingController' yet.
So, How to using 'WCSessionDelegate'?
I tried like that:
Is it the best way to using Delegate in SwiftUI-only code?
And how can I changing the 'showMessage'?
Thanks!
In the code:
Code Block swift import SwiftUI @main struct MySwiftAppApp: App { @SceneBuilder var body: some Scene { WindowGroup { NavigationView { ContentView() } } WKNotificationScene(controller: NotificationController.self, category: "LandmarkNear") } }
Here is no 'WKHostingController' yet.
So, How to using 'WCSessionDelegate'?
I tried like that:
Code Block swift import SwiftUI import WatchConnectivity struct WatchInfo: View { @State private var showMessage: String = "Wating" init() { ABWatchSessionManager.sharedInstance.addDelegateObject(WatchSessionDelegate()) } var body: some View { Text(showMessage) } class WatchSessionDelegate: NSObject, WCSessionDelegate { func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { let data: Dictionary<String, String> = message["data"] as! Dictionary<String, String> if data["dataType"] == DataType.ping.rawValue { } else if data["dataType"] == DataType.data.rawValue { } } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) { } } } struct WatchInfo_Previews: PreviewProvider { static var previews: some View { WatchInfo() } }
Is it the best way to using Delegate in SwiftUI-only code?
And how can I changing the 'showMessage'?
Thanks!
I found a way:
Code Block swift import SwiftUI import WatchConnectivity struct WatchInfo: View { @State private var showMessage: String = "Wating" var body: some View { VStack { Text(showMessage).onAppear() { ABWatchSessionManager.sharedInstance.addDelegateObject(WatchSessionDelegate(self)) } } } class WatchSessionDelegate: NSObject, WCSessionDelegate { var parent: WatchInfo init(_ watchInfo: WatchInfo) { self.parent = watchInfo } func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { let data: Dictionary<String, String> = message["data"] as! Dictionary<String, String> if data["dataType"] == DataType.ping.rawValue { parent.showMessage = "Get PING" } else if data["dataType"] == DataType.data.rawValue { parent.showMessage = "Get DATA" } } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) { } } } struct WatchInfo_Previews: PreviewProvider { static var previews: some View { WatchInfo() } }