iPhone与iWatch连接、控制、数据传递(Swift)的方法

2020-01-08 23:45:57王振洲

调用方法:

1、首先在iPhone的AppDelegate的didFinishLaunchingWithOptions函数中添加代码

IwatchSessionUtil.shareManager.startSession(),确保WCSession能匹配到watch侧的App

              2、发送消息:调用方法IwatchSessionUtil.shareManager.sendMessageToWatch(key: , value: )即可,发送后接收到watch侧的回复后的操作,直接在类sendMessage函数中编辑就行

              3、watch侧sendMessage发送信息给iPhone,iPhone侧didReceiveMessage接收到信息,一系列操作上面已经注释写到。

iPhone端的介绍完毕,下面写watch端的代码,其实跟iPhone的没什么区别,这里只是为了把这部分内容写完全。


import WatchKit
import WatchConnectivity
class WatchSessionUtil: NSObject,WCSessionDelegate {
  // 静态单例
  static let sharedManager = WatchSessionUtil()
  // 初始化
  private override init()
  {
    super.init()
  }
  // 连接机制
  private let session:WCSession? = WCSession.isSupported() ? WCSession.default() : nil
  // 激活机制
  func startSession(){
    session?.delegate=self
    session?.activate()
  }
  // 检测到iPhone的父应用
  func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
  }
  // 接收到iPhone端发送过来的信息
  // message: iPhone端发送过来的信息
  // replyHandler: watch端回复给iPhone的内容
  func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    // 这里也可以通过通知中心发送通知给InterfaceController,进行页面操作,至于用什么方法大家随意。注意事项iPhone的代码里提到了,一样的性质,这里就不写了。
  }
  // 向iPhone侧发送信息
  func sendMessage(key:String, value:Any){
    session?.sendMessage([key : value], replyHandler: { (reply: [String : Any]) in
      // 信息发送之后,收到iPhone端回复的操作
    }, errorHandler: { (Error) in
      // 发送失败
    })
  }
}

watch的类添加在Extension的文件夹中,调用方法:

1、ExtensionDelegate文件的applicationDidFinishLaunching函数里写上WatchSessionUtil.sharedManager.startSession()

2、发送消息:调用方法IwatchSessionUtil.shareManager.sendMessageToWatch(key: , value: )即可,发送后接收到iPhone侧的回复后的操作,直接在类sendMessage函数中编辑就行

3、iPhone侧sendMessage发送信息给watch,watch侧didReceiveMessage接收到信息,一系列操作上面已经注释写到。

以上所述是小编给大家介绍的iPhone与iWatch连接、控制、数据传递(Swift)的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!