问题描述
我需要一些帮助,以其他方式将数据从Watch发送到iPhone。 如果我将手表中的数据发送到iPhone,并且iPhone应用程序不在多任务处理中,则一旦打开iPhone应用程序,数据就会更新。 但是,如果我将数据从iPhone发送到手表,则只有在手表应用可见的情况下,它才会在手表上更新。 如果应用程序在后台运行,我将无法正常工作。有什么建议? 非常感谢你!
InterfaceController
import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController {
@IBOutlet weak var dataFromPhoneLabel: WKInterfaceLabel!
let session = WCSession.default
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
session.delegate = self
session.activate()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func sendDataToPhoneButtonTapped() {
let dataToPhone: [String: Any] = ["watch": "FromWatch" as Any]
session.sendMessage(dataToPhone,replyHandler: nil,errorHandler: nil)
}
}
extension InterfaceController: WCSessionDelegate {
func session(_ session: WCSession,activationDidCompleteWith activationState: WCSessionActivationState,error: Error?) {
//
}
func session(_ session: WCSession,didReceiveMessage message: [String : Any]) {
if let valueFromPhone = message["phone"] as? String {
self.dataFromPhoneLabel.setText(valueFromPhone)
}
}
}
ViewController
import UIKit
import WatchConnectivity
class ViewController: UIViewController {
@IBOutlet weak var phonetoWatchTextField: UITextField!
var session: WCSession?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if WCSession.isSupported() {
session = WCSession.default
session.delegate = self
session.activate()
}
}
@IBAction func sendToWatchButtonTapped(_ sender: Any) {
if let validSession = self.session,validSession.isReachable {
let dataToWatch: [String: Any] = ["phone": phonetoWatchTextField.text as Any]
validSession.sendMessage(dataToWatch,errorHandler: nil)
}
}
}
extension ViewController: WCSessionDelegate {
func sessionDidBecomeInactive(_ session: WCSession) {
//
}
func sessionDidDeactivate(_ session: WCSession) {
//
}
func session(_ session: WCSession,error: Error?) {
//
}
func session(_ session: WCSession,didReceiveMessage message: [String : Any]) {
dispatchQueue.main.async {
if let valueFromWatch = message["watch"] as? String {
phonetoWatchTextField.text = valueFromWatch
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)