Is it possible to send a notification to an iPhone from the paired Apple Watch on a button press in my app on the watch?
Send notification to iPhone from Apple Watch in Swift
Yes.
I did it this way:
- create an IBAction (that I linked to a tap on a label).
- Here it is to ask for a sync between iPhone and Watch
- synced done is displayed on the Watch in:
@IBOutlet weak var autonomyMessage: WKInterfaceLabel!
IBAction:
@IBAction func tapOnConnectionToIphone(_ sender: Any) {
autonomyMessage.setText("")
let session = WCSession.default
if session.isReachable {
session.sendMessage(["request" : "sync"], replyHandler: { (response) in
self.autonomyMessage.setText(NSLocalizedString("Received!", comment: "SessionInterfaceController"))
}, errorHandler: { (error) in
self.autonomyMessage.setText(NSLocalizedString("Not received!", comment: "SessionInterfaceController"))
})
autonomyMessage.setText(NSLocalizedString("Sent!", comment: "SessionInterfaceController"))
} else {
autonomyMessage.setText(NSLocalizedString("Not sent!", comment: "SessionInterfaceController"))
}
autonomyMessage.setHidden(false)
}
On the iPhone side:
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
if message["request"] as? String == "sync" {
// proceed as needed
}
}
For SwiftUI, you'd only need to translate the Watch side of what was provided by @Claude31, similar to this:
struct ScheduleNotificationOnPhoneView: View {
@State private var result = ""
func sendMessageToPhone() {
let session = WCSession.default
guard session.isReachable else {
result = "Session is not reachable."
return
}
session.sendMessage(["request": "scheduleNotification"],
replyHandler: { _ in
// You probably want to parse the reply here to handle the reply from your phone
result = "Notification request sent to phone."
}, errorHandler: {
result = "Error sending request: \($0.localizedDescription)"
})
}
var body: some View {
VStack {
Button("Schedule on Phone") {
sendMessageToPhone()
}
}
}
}
In UIKit case, iPhone side goes into the viewController that handles the message (in my case, the initial VC)