Я делаю приложение для 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()
}
}