今天突然想起来搞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")
}
}
本文介绍了一个使用 MMWormhole 实现 Apple Watch 和 iPhone 间通信的例子。通过应用组标识符和目录名设置 MMWormhole,并在 iPhone 和 Watch 上分别监听消息标识符,实现了按钮操作的数据同步。
828

被折叠的 条评论
为什么被折叠?



