IPhone and iWatch connection, control, data transmission (Swift), iPhone iWatch

Source: Internet
Author: User
Tags notification center

IPhone and iWatch connection, control, data transmission (Swift), iPhone iWatch

Recently, I was working on a project involving iPhone devices and watches to transmit data and control the interaction between interfaces. I found a lot of information on the Internet and found that there are not many websites in China, the foreign websites are not fully written, so I am writing this blog here for your reference. Hope you can give me some advice.

There is no need to talk about pairing iPhone and iWatch. Baidu has a lot of answers, which is the premise.

The code for iPhone and iWatch interaction is dependent on the iWatch system. The iWatch OS1 and OS2 and 3 methods are different. In the OS1 system, the iWatch code for sending data is as follows:

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

This function is used to send messages and receive messages. The reply to the iPhone is replyInfo. In the iPhone AppDelegate, the code for receiving 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.

The above Code only applies to watchOS1, and the subsequent system will not have this API. For OS2 or OS3, the framework used is WatchConnectivity. Here, I will provide the classes I wrote directly, it also provides an introduction and usage method. You can directly copy the code and write your own functions in the place where I comment.

The following is the iPhone code:

Import UIKitimport WatchConnectivityclass IwatchSessionUtil: NSObject, WCSessionDelegate {// static Singleton static let shareManager = IwatchSessionUtil () // initialize 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 ()} // The watch app func session (_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) is detected ?) {Print ("AppleWatch matched")} // start to pass data func sessionDidBecomeInactive (_ session: WCSession) {}// func sessionDidDeactivate (_ session: WCSession) to Watch) {} // send data from the watch side. The iPhone receives the data and replies to the Data. // message: the message sent from the watch side // replyHandler: the iPhone replies to the past func session (_ session: WCSession, didReceiveMessage message: [String: Any], replyHandler: @ escaping ([String: Any])-> Void) {// here, we receive the watc H. You can use a proxy, code block, or notification center to send values to ViewController to perform a series of operations. // Note !!: The message sent from the watch side. The iPhone replies directly to replyHandler ([String: Any]) (replyHandler (data) in this function )), in this way, reply corresponding to the function sending data on the watch side can receive the data. Do not confuse it with sendMessage. If you reply with sendMessage, the watch side receives the message as the didReceiveMessage function.} // The iPhone sends data to watch // key: key value of the data // value: data content func sendMessageToWatch (key: String, value: Any) {session ?. SendMessage ([key: value], replyHandler: {(dict: Dictionary) in // The operation after data is sent, for example, if you write an alert prompt indicating that the message is successfully sent // replyHandler is the content replied by reply after the didReceiveMessage function on the watch side receives the message, you can edit the required functions here}, errorHandler: {(Error) in // failed to send, usually because Bluetooth is not enabled or the mobile phone is in flight mode })}}

 

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

2. Send a message: Call the IwatchSessionUtil method. shareManager. sendMessageToWatch (key:, value:). After sending the message, you can directly edit it in the sendMessage function.

3. The sendMessage on the watch side is sent to the iPhone, and the didReceiveMessage on the iPhone side receives the information. A series of operations have been commented on.

After the iPhone is introduced, write the watch code below, which is actually no different from that of the iPhone. Here we just want to completely write this part of content.

Import WatchKitimport WatchConnectivityclass WatchSessionUtil: NSObject, WCSessionDelegate {// static Singleton static let sharedManager = WatchSessionUtil () // initialize 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 ()} // detects the iPhone's parent app func session (_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error ?) {} // Receives the message sent from the iPhone. // message: the message sent from the iPhone. // replyHandler: func session (_ session: WCSession, didReceiveMessage message: [String: Any], replyHandler: @ escaping ([String: Any])-> Void) {// You can also send a notification to InterfaceController through the notification center, for page operations, you can use any method. Note: I mentioned in the iPhone code that the same nature will not be written here.} // Send the message func sendMessage (key: String, value: Any) {session ?. SendMessage ([key: value], replyHandler: {(reply: [String: Any]) in // action received from the iPhone after the message is sent}, errorHandler: {(Error) in // failed to send })}}

The watch class is added to the Extension folder. The call method is as follows:

1. Write WatchSessionUtil. sharedManager. startSession () in the applicationDidFinishLaunching function of the ExtensionDelegate file ()

2. Send a message: Call the IwatchSessionUtil method. shareManager. sendMessageToWatch (key:, value:). After sending the message, you can directly edit it in the sendMessage function.

3. Send the sendMessage to watch on the iPhone side, and didReceiveMessage on the watch side receives the message. A series of operations have been commented on.

The content is so much, it is very complete, here is the Swift code, OC code I give a URL for your reference: http://blog.csdn.net/shenjie12345678/article/details/61913968

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.