我试图简单地用Xcode仿真器将iOS应用程序连接到watchOS应用程序,并使用手表连接WCSession。手表是不可及的,即使我尝试了对代码的每一个可能的更改,会话也不会激活。我使用相同的同步服务,我把它的目标更改为手表和iOS应用程序,当应用程序开始使用.didAppear时,我就给它们打电话,我做错了什么吗?
import Foundation
import WatchConnectivity
class SyncService : NSObject, WCSessionDelegate {
private var session: WCSession = .default
init(session: WCSession = .default) {
super.init()
self.session = session
self.session.delegate = self
print("Reachable :",session.isReachable)
#if os(iOS)
print("Connection provider initialized on phone")
#endif
#if os(watchOS)
print("Connection provider initialized on watch")
#endif
self.connect()
print("Details",self.session)
}
func connect() {
guard WCSession.isSupported() else {
print("WCSession is not supported")
return
}
switch self.session.activationState {
case .activated:
print("WCSession activated successfully")
case .inactive:
print("Unable to activate the WCSession. Error:")
case .notActivated:
print("Unexpected .notActivated state received after trying to activate the WCSession")
@unknown default:
print("Unexpected state received after trying to activate the WCSession")
}
session.activate()
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
#if os(iOS)
func sessionDidBecomeInactive(_ session: WCSession) { }
func sessionDidDeactivate(_ session: WCSession) { }
#endif
// func sendMessage(_ key: String, _ message: String, _ errorHandler: ((Error) -> Void)?) {
// if session.isReachable {
// session.sendMessage([key : message], replyHandler: nil) { (error) in
// print(error.localizedDescription)
// if let errorHandler = errorHandler {
/// errorHandler(error)
// }
// }
// }
// }
}import SwiftUI
@main
struct Connectivity_Watch_AppApp: App {
var body: some Scene {
WindowGroup {
ContentView() .onAppear{
var model = SyncService()
}
}
}
}import SwiftUI
@main
struct ConnectivityApp: App {
var body: some Scene {
WindowGroup {
ContentView() .onAppear{
var model = SyncService()
}
}
}
}发布于 2022-11-28 19:19:34
您必须等到会话被激活,然后才能发送消息。因此,请检查是否激活了会话,然后发送消息。
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if activationState == .activated {
// send message
}
}https://stackoverflow.com/questions/74604481
复制相似问题