我正在为 watchOS 制作一个旨在接收一些通知的应用程序,发送这些通知的设备是 iPhone。
我已经设法在 Apple Watch 和 iPhone 之间进行通信,并且 iPhone 已经向 Apple Watch 发送消息,Apple Watch 也已经向 iPhone 发送消息。我没有使用该WatchNotification
工具。
发生的事情如下,当我运行应用程序时,它会自动在 Apple Watch 中打开,我想要的是应用程序保持在后台运行。当我按下 iPhone 中的按钮时,会向 Apple Watch 发送一条文本,然后(当 Apple Watch 接收到文本时)应用程序才能正常打开。
我会很感激任何帮助。
iPhone 代码
import UIKit
import WatchConnectivity
class ViewController: UIViewController,WCSessionDelegate {
var iphoneNotification = "Deseja renovar o seu seguro automovel?"
let session = WCSession.defaultSession()
@IBOutlet weak var lblNotification: UILabel!
override func viewDidLoad() {
initSession()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func ActionSentNotification(sender: AnyObject) {
let msg = ["NotificationSentforIphone" : iphoneNotification]
session.sendMessage(msg, replyHandler: {(replay) -> Void in }) { (error) -> Void in
}
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject])
{
let msg = message["NotificationSentforWatch"] as! String
lblNotification.text = "\(msg)"
}
func initSession()
{
session.delegate = self
session.activateSession()
}
}
观看代码
import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController,WCSessionDelegate {
@IBOutlet var Notification: WKInterfaceLabel!
var watchNotification = "ok"
let session = WCSession.defaultSession()
//@IBOutlet var lblNotification: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
initSession()
super.willActivate()
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject])
{
let msg = message["NotificationSentforIphone"] as! String
Notification.setText("\(msg)")
//lblNotification.setText("Notification:\(msg)")
}
@IBAction func ActionSentNotificationforIphone()
{
let msg = ["NotificationSentforWatch" : watchNotification]
session.sendMessage(msg, replyHandler: {(replay) -> Void in }) { (error) -> Void in
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func initSession()
{
session.delegate=self
session.activateSession()
}
}