iPhone and iWatch connect control data transfer (Swift) methods

  • 2020-05-19 06:01:27
  • OfStack

Recently, I have been doing a project, involving the iPhone equipment and watches to transmit data and control the interface of each other. I have found a lot of information on the Internet, and found that the domestic website does not introduce much in this aspect, while the foreign website is not very complete, so I write this article here, for everyone to refer to 1, looking at god pointing out 12.

iPhone and iWatch match this need not say more, baidu search answer 1 a lot, this is the premise.

The code that iPhone interacts with iWatch comes in two forms, depending on iWatch's system. iWatch OS1 is different from OS2 and 3. In the system of OS1, iWatch sends data as follows


let userInfo:[String:String] = ["key":"value"]
WKInterfaceController.openParentApplication(userInfo) { (replyInfo, error) -> Void in
}

This function is both sending and receiving messages, and the response from iPhone is replyInfo. In AppDelegate at iPhone, the code to receive the message is:


func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
}

The message received is userInfo, and the data returned to iWatch is reply.

For OS2 or OS3, the framework used is WatchConnectivity. Here, I will directly provide the class I wrote, and give the introduction and use methods. You can directly copy the code, and write your own functions in the place I commented.

Here is the code of iPhone:


import UIKit
import WatchConnectivity
class IwatchSessionUtil: NSObject, WCSessionDelegate {
  // Static singleton 
  static let shareManager = IwatchSessionUtil()
  // Initialize the 
  private override init()
  {
    super.init()
  }
  //  Connection mechanism 
  private let session:WCSession? = WCSession.isSupported() ? WCSession.default() : nil
  //  Activation mechanism object 
  func startSession(){
    session?.delegate = self
    session?.activate()
  }
  //  detected watch end app
  func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    print("AppleWatch Matching complete ")
  }
  //  Began to Watch To transfer data 
  func sessionDidBecomeInactive(_ session: WCSession) {
  }
  //  The data is done 
  func sessionDidDeactivate(_ session: WCSession) {
  }
  // watch Send data from the side, iPhone Receive data and revert data to the past 
  // message: watch A message sent from the side 
  // replyHandler: iPhone Reply to past messages 
  func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    //  Here, we receive watch The data sent can be sent by proxy, a code block, or a notification center ViewController To make 1 Serial operations. 
    //  Note!!!!! : watch The side sends the information, iPhone Reply directly in this function replyHandler([String : Any]) ( replyHandler( data ) ) so that watch The function corresponding to the side sending data reply To receive data. Don't follow sendMessage This function gets confused. If you use sendMessage Reply, watch The side receives the message didReceiveMessage The function. 
  }
  // iPhone to watch To send data 
  // key:  The data of key value 
  // value:  The data content 
  func sendMessageToWatch(key:String,value:Any) {
    session?.sendMessage([key : value], replyHandler: { (dict:Dictionary) in
    //  Here's what you do after you send the data, like write a alert Prompt sent successfully 
   // replyHandler is watch side didReceiveMessage The function receives the information reply Reply to the content, here you can edit their own needs 
    }, errorHandler: { (Error) in
      //  Sending failed, 1 Bluetooth is not on, or the mobile phone on flight mode 
    })
  }
}

Call method:

1. First add code to iPhone's AppDelegate's didFinishLaunchingWithOptions function

IwatchSessionUtil.shareManager.startSession (), making sure that WCSession matches App on the watch side

2. Send message: call the method IwatchSessionUtil.shareManager.sendMessageToWatch (key:, value:), and then receive the reply from watch side, and directly edit it in the sendMessage function

3. watch side sendMessage sends information to iPhone, didReceiveMessage side iPhone receives information, 1 series of operations have been noted above.

So that's the end of the iPhone, and now I'm going to write the code for the watch, which is no different than the code for the iPhone, just to make it complete.


import WatchKit
import WatchConnectivity
class WatchSessionUtil: NSObject,WCSessionDelegate {
  //  Static singleton 
  static let sharedManager = WatchSessionUtil()
  //  Initialize the 
  private override init()
  {
    super.init()
  }
  //  Connection mechanism 
  private let session:WCSession? = WCSession.isSupported() ? WCSession.default() : nil
  //  The activation mechanism 
  func startSession(){
    session?.delegate=self
    session?.activate()
  }
  //  detected iPhone The parent application 
  func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
  }
  //  To receive iPhone A message sent from the end 
  // message: iPhone A message sent from the end 
  // replyHandler: watch The reply to iPhone The content of the 
  func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    //  You can also send notifications to the notification center here InterfaceController , the page operation, as to use what method you are free. Matters needing attention iPhone And it says in the code, 1 I'm not going to write it here. 
  }
  //  to iPhone Side send 
  func sendMessage(key:String, value:Any){
    session?.sendMessage([key : value], replyHandler: { (reply: [String : Any]) in
      //  After the message is sent, it is received iPhone The operation of the end reply 
    }, errorHandler: { (Error) in
      //  Send failure 
    })
  }
}

watch's class is added to the Extension folder, and the method is called:

1. In the applicationDidFinishLaunching function of ExtensionDelegate file, write WatchSessionUtil.sharedManager.startSession ()

2. Send message: call the method IwatchSessionUtil.shareManager.sendMessageToWatch (key:, value:), and then receive the reply from iPhone side after sending, and edit it directly in the sendMessage function

3. iPhone side sendMessage sends information to watch, watch side didReceiveMessage receives information, series 1 operation has been commented above.


Related articles: