IOS应用和watch应用的通信

本文介绍了一个使用 MMWormhole 实现 Apple Watch 和 iPhone 间通信的例子。通过应用组标识符和目录名设置 MMWormhole,并在 iPhone 和 Watch 上分别监听消息标识符,实现了按钮操作的数据同步。

今天突然想起来搞apple watch,就想做一下iPhone 和watch之间的通信,搞来搞去,搞不出个所以然,于是想起了伟大的github,在github上找到了这个MMWormhole效果如下
这里写图片描述

唯一不好的地方是用MMWormhole项目必须要支持APP groups,如果不知道的同学们,请Google之
下面贴一下代码

//这是iPhone应该的代码
class ViewController: UIViewController {
    @IBOutlet var label: UILabel!
    //初始化MMWormhole  group.LKK.com.test是group的标示符 ceshi是目录名
    var wormhole = MMWormhole(applicationGroupIdentifier: "group.LKK.com.test", optionalDirectory: "ceshi")
    //减少按钮的方法
    @IBAction func down(sender: AnyObject) {
        //发送消息第一个参数是你需要传递的参数,第二个参数是是消息标示符
        self.wormhole.passMessageObject(["AddSubtract" : "down"], identifier: "AddSubtract")
    }
    //增加按钮的方法
    @IBAction func add(sender: AnyObject) {
        self.wormhole.passMessageObject(["AddSubtract" : "add"], identifier: "AddSubtract")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //监听tap这个消息,如果收到,进入回调方法
        self.wormhole.listenForMessageWithIdentifier("tap", listener: { (MessageObject) -> Void in
            self
          self.label.text = MessageObject["tap"] as NSString
        })

    }
}
//这是watch页面的代码
class InterfaceController: WKInterfaceController {

    @IBOutlet var numbelLabel: WKInterfaceLabel!
    var num = 0;
    var wormhole = MMWormhole(applicationGroupIdentifier: "group.LKK.com.test", optionalDirectory: "ceshi")
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        //监听
        self.wormhole.listenForMessageWithIdentifier("AddSubtract", listener: { (messageObject) -> Void in
            var str = messageObject["AddSubtract"] as NSString

            if(str.isEqualToString("down")){
                self.num--;
            }
            if(str.isEqualToString("add")){
                self.num++;
            }
            self.numbelLabel.setText("\(self.num)")
        })

    }
    //下面是三个按钮的方法
    @IBAction func tapThree() {
        //发送消息
         self.wormhole.passMessageObject(["tap" : "three"], identifier: "tap")
    }
    @IBAction func tapOne() {
        //发送消息
         self.wormhole.passMessageObject(["tap" : "one"], identifier: "tap")
    }
    @IBAction func tapTwo() {
        //发送消息
         self.wormhole.passMessageObject(["tap" : "two"], identifier: "tap")
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值