简体   繁体   English

Watch Connectivity首次使用,但此后没有

[英]Watch Connectivity works the first time but not after that

I've tested on the Simulator and Device, somehow Watch Connectivity stops working after it's used once. 我已经在Simulator和Device上进行了测试,一旦使用Watch Watch Connectivity ,它就会以某种方式停止工作

I'm passing data from Watch -> iPhone, and it only works once and then stops after that. 我从Watch-> iPhone传递数据,它只能运行一次 ,然后在此之后停止。

Any ideas? 有任何想法吗?

iPhone ViewController : iPhone ViewController

var session: WCSession?

override func viewDidLoad() {
    super.viewDidLoad()
    if WCSession.isSupported() {
        session = WCSession.default()
        session?.delegate = self
        session?.activate()
    }
}

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    // Received Application Context from Watch
    let type = applicationContext["watchType"]
    print("Type iPhone: \(type)")

    DispatchQueue.main.async {
        self.type.text = "Type: \(type)"
    }

}

Watch InterfaceController : 观看InterfaceController

let session = WCSession.default()

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    if WCSession.isSupported() {
        session.delegate = self
        session.activate()
    }
}

@IBAction func startPressed() {
    saveEverything()
}

func saveEverything() {
    let watchContextType = ["watchType" : "Boxing/Running"]

    do {
        print("Type Watch: \(watchContextType)")
        try session.updateApplicationContext(watchContextType)
    } catch {
        print("Didn't work")
    }
}

When you use the updateApplicationContext() , you need to change the parameters for each call, otherwise the msg will not be delivered. 当使用updateApplicationContext() ,您需要更改每个调用的参数,否则将不发送msg。 I belive this is to conserve battery. 我相信这是为了节省电池。

Anyway, try sending your message using sendMessage() or sendMessageData() , then the messages get delivered each time, even when they have the same contents. 无论如何,尝试使用sendMessage()sendMessageData()发送消息,即使消息内容相同,每次也会传递消息。 And, they are higher priority than updateApplicationContext so it's win-win :) 而且,它们的优先级高于updateApplicationContext因此是双赢的:)

Here is the documentation: https://developer.apple.com/library/content/documentation/General/Conceptual/WatchKitProgrammingGuide/SharingData.html#//apple_ref/doc/uid/TP40014969-CH29-SW1 这是文档: https : //developer.apple.com/library/content/documentation/General/Conceptual/WatchKitProgrammingGuide/SharingData.html#//apple_ref/doc/uid/TP40014969-CH29-SW1

If you want to Drain Battery of your apple watch app Quickly then above technique of @Jens is well and good. 如果您想快速耗尽Apple Watch App的电池,那么@Jens的上述技巧很好。


Instead of shifting from updateApplicationContext() to sendMessage() better make small change in your project to get Desired result. 与其从updateApplicationContext()更改为sendMessage(),不如在项目中进行一些小的更改以获得所需的结果。


I will explain the question scenario and then solution along with Demo app :- 我将解释问题场景 ,然后与演示应用程序一起解决:-

在此处输入图片说明

 @IBAction func sliderChange(_ value: Float)

{
    let str:String?
    switch value {
    case 0...7 :
          str = "Running"
    case 8...14 :
          str = "Sleeping"
    default:
        str = "normal"
    }
     updateContext(value: str!)
}

func updateContext(value:String) {
    let dictionary = [ "watchType" : value ]
    do {
        print("update application context is called do statemet")
        try session?.updateApplicationContext(dictionary)
    }
    catch{
        print("this is the catch statement")
    }
}

With update in slider Values in Watch ,iPhone values get updated .As you can see there is repetition of values for iPhone ie 通过Watch滑块中的Values更新,iPhone值会更新。如您所见,iPhone的值存在重复,即

When sliderValue are from 0 to 7 values remain "Running" && "Sleeping" for 8 to 14 . 当SliderValue从0到7时,“ Running”和“&Sleeping”值保持8到14。

App work fine if I varies values of slide and desired result is reflected in iPhone in normal scenario. 如果我更改幻灯片的值,并且正常情况下在iPhone中反映了所需的结果,则应用程序工作正常。

Scenrio where it fails :- i)Change the slider values from 0 to 3 then "Running" is reflected in iPhone. 失败的情况 :-i)将滑块值从0更改为3,然后“ Running”会反映在iPhone中。 Thant's fine . Thant很好。 ii)Now close the iPhone application then change the slider values from 3 to 5 no we can see real problem when iPhone is opened back. ii)现在关闭iPhone应用程序,然后将滑块值从3更改为5,不,打开iPhone后我们看不到真正的问题。 iii) Values is not triggered to iPhone . iii) iPhone不会触发值

在此处输入图片说明

Due to internal caching mechanism of updateApplicationContext() restrict to trigger of duplicate values to iPhone . 由于updateApplicationContext()的内部缓存机制,限制了对iPhone重复值的触发。

Store the last updated state in didReceiveApplicationContext() and display state according to stored value . 将最后更新的状态存储在didReceiveApplicationContext()中,并根据存储的值显示状态。

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        checkStatus()
        updateSavedState()
    }
    func checkStatus() {
        print("check status")
        if WCSession.isSupported() {
            session = WCSession.default()
            session?.delegate = self
            session?.activate()
        }
    }

     func session(_ session: WCSession, didReceiveApplicationContext    applicationContext: [String : Any]) {
        let type = applicationContext["watchType"]!
         DispatchQueue.main.async {
            self.updateLabel.text =  " Type: \(type)"
            UserDefaults.standard.set(type, forKey: "savedState") //setObject
        }
    }

    func updateSavedState() {
        self.updateLabel.text = UserDefaults.standard.string(forKey: "savedState")
    }

Now everything is work perfect. 现在一切都完美无缺。 Demo App . 演示应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM