Connection, Control, Data Transfer (Swift) between the iPhone and iWatch

Recently, in a project involving the transmission of data and the control of interface jump between the iPhone devices and watches, I searched a lot of information on the Internet, and found that the domestic websites were not introduced much, while the foreign websites were not very complete, so I am writing this blog here to give you a reference and look forward to God's advice. One or two.

The combination of the iPhone and iWatch does not need to say much about this. Baidu has a lot of search answers, which is the premise.

The code that the iPhone interacts with iWatch has two scenarios, depending on the iWatch system. iWatch OS1 is different from OS2 and OS3. In OS1 system, iWatch sends data as follows

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

This function is to send and receive messages, and replyInfo is the reply received from the iPhone. In AppDelegate on the iPhone side, the code that receives the message:

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

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

For OS2 or OS3, the framework used is Watch Connectivity. Here, I will provide the classes I wrote directly, and give the introduction and use method. You can copy the code directly, and write your own functions in the place I commented on. .

Here's the code for the iPhone:

import UIKit
import WatchConnectivity

class IwatchSessionUtil: NSObject, WCSessionDelegate {
    //Static singleton
    static let shareManager = IwatchSessionUtil()
    
    //Initialization
    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()
    }
    
    // Detection watch end app
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        print("AppleWatch Matching Completion")
    }
    
    // Begin to Watch Transfer of data
    func sessionDidBecomeInactive(_ session: WCSession) {
    }
    
    // The data has been transferred.
    func sessionDidDeactivate(_ session: WCSession) {
    }
    
    // watch Side send data, iPhone Receive data and reply to the past
    // message: watch Information sent from side
    // replyHandler: iPhone Respond to past information
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        // Here we receive watch The data sent can be passed to a proxy, code block, or notification center. ViewController,Make a series of operations.
       // Note!! : watch The message is sent to the side. iPhone Reply directly in this function replyHandler([String : Any])(replyHandler(data)),such watch The function corresponding to the side sending data reply To receive data, don't follow sendMessage This function is confused. If used sendMessage Answer, that watch Side received information is didReceiveMessage A function of.
    }
    
    // iPhone towards watch send data
    // key: Data key value
    // value: Data content
    func sendMessageToWatch(key:String,value:Any) {
        session?.sendMessage([key : value], replyHandler: { (dict:Dictionary) in
        // Here is the operation after sending data, such as writing a alert Successful prompt
    // replyHandler yes watch side didReceiveMessage After the function receives the information reply Here you can edit the functions you need.
        }, errorHandler: { (Error) in
            // Send failure, usually Bluetooth is not on, or mobile phone is on flight mode.
        })
    }
}

 

Call method: 1. First, add the code IwatchSessionUtil.shareManager.startSession() to the DidFinish Launching WithOptions function of AppDelegate of the iPhone to ensure that WCSession matches the App on the watch side.

2. Send a message: Call the method IwatchSessionUtil. ShareManager. sendMessageToWatch (key:, value:) and then receive the response from the watch side. Edit it it directly in the sendMessage-like function.

3. sendMessage on the watch side sends information to the iPhone, didReceiveMessage on the iPhone side receives information, and a series of operations have been annotated above.

After the introduction of the iPhone side, the following code is written on the watch side, which is no different from the iPhone. This is just to write this part completely.

import WatchKit
import WatchConnectivity

class WatchSessionUtil: NSObject,WCSessionDelegate {
    // Static singleton
    static let sharedManager = WatchSessionUtil()
    
    // Initialization
    private override init()
    {
        super.init()
    }
    
    // Connection mechanism
    private let session:WCSession? = WCSession.isSupported() ? WCSession.default() : nil
    
    // Activation mechanism
    func startSession(){
        session?.delegate=self
        session?.activate()
    }
    
    // Detection iPhone The parent application of the
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    }
    
    // Received iPhone Information sent from the end
    // message: iPhone Information sent from the end
    // replyHandler: watch End-to-end reply iPhone Contents
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
       // Notification can also be sent here through the Notification Center. InterfaceController,Page operation, as to what method we use at will. Matters needing attention iPhone As mentioned in the code, the same nature is not written here.
    }
    
    // towards iPhone Side Send Information
    func sendMessage(key:String, value:Any){
        session?.sendMessage([key : value], replyHandler: { (reply: [String : Any]) in
           // After the message is sent, it is received. iPhone End-to-end recovery operation
        }, errorHandler: { (Error) in
            // fail in send
        })
    }
}

The watch class is added to the Extension folder and the method is called:

1. Write WatchSessionUtil.sharedManager.startSession() in the application DidFinish Launching function of the Extension Delegate file.

2. Send a message: Call the method IwatchSessionUtil. ShareManager. sendMessageToWatch (key:, value:) and receive the response from the iPhone side after sending, edit it directly in the sendMessage-like function.

3. sendMessage on the iPhone side sends information to watch, didReceiveMessage on the watch side receives information, and a series of operations have been annotated above.

So much, it's already complete. Here's Swift code, OC code. Let me refer to a website: http://blog.csdn.net/shenjie12345678/article/details/61913968.

Tags: iOS Session Mobile Swift

Posted on Sun, 14 Jul 2019 14:52:01 -0700 by dmcentire