私はいくつかの通知を受け取ることを目的とした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()
}
}