Currently trying to create an app that sends data/a message from an Apple Watch to a linked iPhone using WCSession. Code compiles with no errors, but only opens the iOS simulator and says that the WCSession isn't paired. I am therefore not able to test the program.
I tried opening the watchOS simulator and trying another simulator, but it hasn't worked. Here is the code in case that is the issue.
WATCH APP
import SwiftUI
import WatchConnectivity
class ContentViewModel: NSObject, ObservableObject, WCSessionDelegate {
@Published var message: String = ""
override init() {
super.init()
setupWatchConnectivity()
}
func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.default
session.delegate = self
session.activate()
}
}
func sendMessageToPhone() {
if WCSession.default.isReachable {
let message = ["text": "Hello, iPhone!"]
WCSession.default.sendMessage(message, replyHandler: nil, errorHandler: nil)
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// Handle activation completion
}
func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
if let text = message["text"] as? String {
DispatchQueue.main.async {
self.message = text
}
}
}
}
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
var body: some View {
VStack {
Text("Message from iPhone:")
Text(viewModel.message)
.font(.title)
Button(action: viewModel.sendMessageToPhone) {
Text("Send Message to iPhone")
}
}
.onAppear {
viewModel.setupWatchConnectivity()
}
}
}
iOS APP
import SwiftUI
import WatchConnectivity
class ContentViewModel: NSObject, ObservableObject, WCSessionDelegate {
@Published var message: String = ""
override init() {
super.init()
setupWatchConnectivity()
}
func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.default
session.delegate = self
session.activate()
}
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// Handle activation completion
}
func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
if let text = message["text"] as? String {
DispatchQueue.main.async {
self.message = text
}
}
}
}
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
var body: some View {
VStack {
Text("Message from Apple Watch:")
Text(viewModel.message)
.font(.title)
}
.onAppear {
viewModel.setupWatchConnectivity()
}
}
}