快速在后台如何在Watch和iPhone之间共享数据 [英] swift how to share data between Watch and iPhone on background

查看:242
本文介绍了快速在后台如何在Watch和iPhone之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实用的应用程序,可以在iPhone和Watch之间共享数据(共享文本),并且我希望即使在将手表置于后台时也能正常工作(当Watch处于后台时从iPhone发送数据到Watch).我读了很多有关如何做到这一点的内容,但是对于我的应用程序似乎没什么问题.请添加代码以使应用程序正常工作.或者给我一些适合这个程序的资源.谢谢!

I have a functional application for sharing the data between iPhone and Watch (share text) and I want to make it work even when the watch is set on background (send data from iPhone to Watch when Watch is on background). I read a lot about how to make this but nothing seemd to be ok for my application. Please add the code to make application work as I said before. Or give me some source which fit with this app. Thank you!

iPhone代码:

    import UIKit
    import WatchConnectivity
    class ViewController: UIViewController, WCSessionDelegate {

    @IBOutlet weak var iPhoneLabel: UILabel!
    var session : WCSession!;

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {

    }

    func sessionDidBecomeInactive(_ session: WCSession) {

    }

    func sessionDidDeactivate(_ session: WCSession) {

    }

    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        let msg = message["b"] as? String;
        self.iPhoneLabel.text = msg;

    }



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func sendMessage(_ sender: Any) {
         session.sendMessage(["a" : "Hello"], replyHandler: nil, errorHandler: nil);
    }
}

观看代码:

    import WatchKit
    import Foundation
    import WatchConnectivity
    import UIKit

    class InterfaceController: WKInterfaceController, WCSessionDelegate {

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {

    }


    @IBOutlet var WatchLabel: WKInterfaceLabel!
    var session: WCSession!;

    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        //self.label.setText(message["a"]! as? String)


        let msg = message["a"] as? String;
        WatchLabel.setText(msg);
        sendMessage();



    }

    func sendMessage(){
         session.sendMessage(["b":"goodbye"], replyHandler: nil, errorHandler: nil);
    }


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

        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()

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

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }
   }

在我使用session.updateApplicationContext()更改了session.sendMessage()方法后,它只能工作一次.有什么建议吗?

After I changed the method session.sendMessage() with session.updateApplicationContext() it only works once. Any advice?

iPhone代码:

import UIKit

import WatchConnectivity


class ViewController: UIViewController, WCSessionDelegate {


@IBOutlet weak var iPhoneLabel: UILabel!

var session : WCSession!;



func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}

func sessionDidBecomeInactive(_ session: WCSession) {
}


 func sessionDidDeactivate(_ session: WCSession) {
}




 func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {



let msg = applicationContext["b"] as? String

//Use this to update the UI instantaneously (otherwise, takes a little while)
DispatchQueue.main.async() {
    self.iPhoneLabel.text = msg;
}

}



override func viewDidLoad() {
super.viewDidLoad()


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


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}


@IBAction func sendMessage(_ sender: Any) {



let applicationDict = ["a":"Hello"];
do {
    try session.updateApplicationContext(applicationDict)
} catch {
    print("error")
}
}

}

代码前观看:

import WatchKit

import Foundation

import WatchConnectivity

import UIKit


class InterfaceController: WKInterfaceController, WCSessionDelegate {


func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {

}


@IBOutlet var WatchLabel: WKInterfaceLabel!
var session: WCSession!;



func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    print("Watch message received")

    let msg = applicationContext["a"] as? String
    DispatchQueue.main.async() {
        self.WatchLabel.setText(msg);
    }
    sendMessage();
}

func sendMessage(){


    print("Watch send message");
    let applicationDict = ["b":"goodbye"];
    do {
        try session.updateApplicationContext(applicationDict)
    } catch {
        print("error")
    }
}


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

    // Configure interface objects here.
}

override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
    super.willActivate()

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

override func didDeactivate() {
    // This method is called when watch view controller is no longer visible
    super.didDeactivate()
}

}

推荐答案

简而言之,即使使用Watch应用程序,也应使用updateApplicationContext方法而不是sendMessage来从iPhone应用程序发送数据.在背景中.有关更多信息,请继续.

In short, you should use the updateApplicationContext method instead of the sendMessage to be able to send data from the iPhone app even when the Watch app is in background. For further info, please continue on.

如果您查看文档,则表明正在调用session.sendMessage如果Watch应用仅在后台运行,则不会唤醒它.

If you look at the documentation, it states that the calling session.sendMessage doesn't wake the Watch app if it is running only in the background.

在WatchKit扩展处于活动状态时调用此方法 并且运行会在后台唤醒相应的iOS应用, 使它可以访问.从您的iOS应用程序调用此方法不会 唤醒相应的WatchKit扩展.如果您调用此方法 并且对方是无法到达的(或在 消息已传递),errorHandler块使用 适当的错误.

Calling this method from your WatchKit extension while it is active and running wakes up the corresponding iOS app in the background and makes it reachable. Calling this method from your iOS app does not wake up the corresponding WatchKit extension. If you call this method and the counterpart is unreachable (or becomes unreachable before the message is delivered), the errorHandler block is executed with an appropriate error.

它还指出,该功能仅在isReachabletrue时有效.

It also states that this function only works if the isReachable is true.

使用sendMessage(:replyHandler:errorHandler :)或sendMessageData(:replyHandler:errorHandler :)方法来传输数据 可达的对手.这些方法旨在立即进行 您的iOS应用和WatchKit扩展之间的通信.这 对于这些方法,isReachable属性当前必须为true 成功.

Use the sendMessage(:replyHandler:errorHandler:) or sendMessageData(:replyHandler:errorHandler:) method to transfer data to a reachable counterpart. These methods are intended for immediate communication between your iOS app and WatchKit extension. The isReachable property must currently be true for these methods to succeed.

要发送用于更新UI的数据,应使用updateApplicationContext(_:)方法,

For sending data that is used to update the UI, you should use the updateApplicationContext(_:) method, using which

系统在机会出现时发送上下文数据, 目标是在对方唤醒时准备好使用数据 上.

The system sends context data when the opportunity arises, with the goal of having the data ready to use by the time the counterpart wakes up.

要使此方法起作用,只需激活session,就不需要将其激活.

For this method to work, the session only needs to be activated, it doesn't need to be reachable.

这篇关于快速在后台如何在Watch和iPhone之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆