I've been working on a project recently , involves iPhone Devices and watches transmit data 、 Control each other interface jump , I found a lot of information on the Internet , I found that the domestic websites didn't introduce much in this aspect , And foreign websites are not very complete , So write this blog here , For your reference , I hope the great God can give me some advice .

iPhone and iWatch I don't need to say much about it , Baidu search answers a lot , This is the premise .

iPhone And iWatch There are two cases of interactive code , Depending on iWatch The system of .iWatch OS1 And OS2、3 Different methods , stay OS1 In the system ,iWatch The code for sending data is as follows

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

This function is to send a message , It's also receiving messages , Received iPhone My reply is replyInfo. stay iPhone Terminal AppDelegate in , The code to receive the message :

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

The message received was userInfo, Reply to iWatch The data of reply.

The above code only applies to watchOS1, Later systems don't have this API 了 , about OS2 or OS3, The framework used is WatchConnectivity, ad locum , I'm going to provide the classes I wrote directly , And give the introduction and usage , You can copy the code directly , Just write your own functions in my notes .

Here are iPhone End of the code :

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 // Activate the session object
func startSession(){
session?.delegate = self
session?.activate()
} // detected watch End app
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("AppleWatch Match complete ")
} // Communication complete, session object idle
func sessionDidBecomeInactive(_ session: WCSession) {
} // Communication complete session object release
func sessionDidDeactivate(_ session: WCSession) {
} // watch Send data from the side ,iPhone Receive the data and reply to it
// message: watch The message from the side
// replyHandler: iPhone Reply to past messages
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
// ad locum , We received watch Data sent , You can use a proxy 、 The code block or the notification center sends the value to ViewController, Make a series of operations .
// notes !!:watch The side sends a message ,iPhone Reply directly in this function replyHandler([String : Any])(replyHandler( data )), such watch The function that side sends data corresponds to reply To receive data , Don't follow sendMessage This function is confusing . If you use sendMessage reply , that watch The message received by the side is didReceiveMessage Function of .
} // iPhone towards watch send data
// key: Data key value
// value: The data content
func sendMessageToWatch(key:String,value:Any) {
session?.sendMessage([key : value], replyHandler: { (dict:Dictionary) in
// Here is the operation after sending the data , For example, write a alert Prompt sent successfully
// replyHandler yes watch Side didReceiveMessage Function receives the message reply The content of the reply , Here you can edit the functions you need
}, errorHandler: { (Error) in
// fail in send , Usually Bluetooth is not on , Or the phone is in flight mode
})
}
}

Calling method :1、 First, in the iPhone Of AppDelegate Of didFinishLaunchingWithOptions Add code to the function IwatchSessionUtil.shareManager.startSession(), Make sure WCSession Can match to watch On the side App

2、 Send a message : Calling method IwatchSessionUtil.shareManager.sendMessageToWatch(key: , value: ) that will do , Send and receive watch Side of the operation after the reply , Directly in class sendMessage Just edit in the function

3、watch Side sendMessage Send a message to iPhone,iPhone Side didReceiveMessage Received information , A series of operations have been annotated as .

iPhone End of introduction , Write the following watch End of the code , In fact, with iPhone It doesn't make any difference , 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()
} // detected iPhone The parent application of
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
 // Communication complete, session object idle 
func sessionDidBecomeInactive(_ session: WCSession) {
} // Communication complete session object release
func sessionDidDeactivate(_ session: WCSession) {
}
 // Received iPhone The information sent by the end 
// message: iPhone The information sent by the end
// replyHandler: watch Reply to iPhone The content of
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
// You can also send a notification to InterfaceController, Page operation , As for what method to use, we are free to . matters needing attention iPhone It's mentioned in our code , The same nature , I won't do that here .
} // towards iPhone Send a message
func sendMessage(key:String, value:Any){
session?.sendMessage([key : value], replyHandler: { (reply: [String : Any]) in
// After the message is sent , received iPhone The operation of end reply
}, errorHandler: { (Error) in
// fail in send
})
}
}

watch Class added in Extension In the folder of , Calling method :

1、ExtensionDelegate Of documents applicationDidFinishLaunching The function says WatchSessionUtil.sharedManager.startSession()

2、 Send a message : Calling method IwatchSessionUtil.shareManager.sendMessageToWatch(key: , value: ) that will do , Send and receive iPhone Side of the operation after the reply , Directly in class sendMessage Just edit in the function

3、iPhone Side sendMessage Send a message to watch,watch Side didReceiveMessage Received information , A series of operations have been annotated as .

That's all there is to it , It's all over the place , What is given here is Swift Code ,OC I'll give you a website to refer to :http://blog.csdn.net/shenjie12345678/article/details/61913968

iPhone And iWatch Connect 、 control 、 Data transfer (Swift) More articles about

  1. [Swift Actual operation ] 8、 ... and 、 Practical advanced -(8) Use performSegue Data transfer between storyboard pages

    This article will demonstrate data transfer between storyboard pages . First, in a blank project , Open the storyboard file that comes with the project (Main.storyboard). You already have a view controller in the storyboard , Click to select the view controller . And then click [Editor ...

  2. JSP Servlet SQL Data transfer among the three

    Preface : I've been doing WEB Development , Now let's sum up our experience and feelings during this period . Bear in mind ,web The development focuses on the front data interaction , Beautify the page instead of indulging in the underlying data . The age of the browser is coming , Call to us more dazzling . More concise . More convenient . A bigger net ...

  3. Dubbo Protocol and connection control

    Protocol Reference Manual (+) (#) Recommended Dubbo agreement Performance test reports the performance of each protocol , Please see the : Performance test report  (+) dubbo:// (+) (#) Dubbo The default protocol is single long connection and NIO Asynchronous communication , optimum ...

  4. 3.2 PCI Data transfer of the device

    PCI The data transmission of the device uses address decoding , When a memory read / write bus transaction arrives PCI Bus time , All the... On this bus PCI The device will decode the address , If the address used by the current bus transaction is in a PCI The equipment BAR In space , The PCI The device will make ...

  5. (Android Data transfer )Intent Message passing mechanism “Intent”“ Data transfer ”

    Intent Class inheritance :   It should be noted that , This class implements Parcelable( For data transfer ) and Cloneable Interface . Intent It's a kind of ( System level ) Message passing mechanism , Can be used within an application , It can also be applied in ...

  6. JSP、servlet、SQL Data transfer between the three

    JSP.servlet.SQL Data transfer between the three Blog classification : web Development JSPservletSQL Database connection pool web Development   Preface : I've been doing WEB Development , Now let's sum up our experience and feelings during this period . Bear in mind , ...

  7. Learn... In seven days ASP.NET MVC ( Two )——ASP.NET MVC Data transfer

    After the first day of study , We believe that you have been right MVC Have some basic knowledge . This section is based on the previous section , So you need to make sure you've got the last section . The goal of this chapter is to use best practice solutions to create a small MV ...

  8. MVC Data transfer

    One . Data transfer 1.ViewData[]: usage :action in :ViewData["key"]="aaa";,V Layer receiving ViewData["key&qu ...

  9. MVC Data transfer and multiple forms

    1. Data transfer (1)session and TempData Global variables , You can pass values from one action to another , It can also be transferred from the control layer to the view layer . TempData Take a value and destroy it automatically . session Use : // The controller ...

Random recommendation

  1. solve poshytip The height of the form is higher than the high end of the screen Show problems

    Poshy Tip Is a very friendly information prompt tool , It's based on jQuery, When you mouse over a link , A message bar will appear . The content of the information can be found directly in HTML It can also be called from the server , The plug-in also provides many properties and methods . ...

  2. PHP Extended writing 、PHP Extended debugging 、VLD Source code analysis 、 Embedded based Embed SAPI Realization opcode see

    catalogue . compile PHP Source code . Extended structure . Advantages and disadvantages . Use PHP Native extension framework wizard ext_skel Write extension . Compilation and installation VLD . Debug debugging VLD . VLD Source code analysis . Embedded ...

  3. URAL 1076 Trash Trash( Maximum weight matching )

    Trash Time limit: 1.0 secondMemory limit: 64 MB You were just hired as CEO of the local junkyard.One ...

  4. hibernate Learning notes 6--Criteria A query 、 Complete exercises ( Development steps )

    One .Criteria The query method does not sql I'm sorry , So be more object-oriented .Criteria It's a ratio. HQL More object-oriented queries :Criteria How to create : Criteria c = s.createCrite ...

  5. strcpy Basic usage

    C Language standard library functions strcpy, Take from src Address starts with and contains NULL The string of the terminator is copied to dest Starting address space . C Language functions Prototype declaration :extern char *strcpy(char* dest, co ...

  6. practice C And SELECT Formal non blocking IO

    ha-ha , I don't understand very well , But after all, it's all in hand , And no mistake . but select.h I don't know where to find the file , Stick it down for a record . POLL,EPOLL It feels like the code is similar , It's just that functions and system implementations are different ,,EPOLL At present, the most reasonable . Accurate positioning , The algorithm is complex ...

  7. utilize Lua Realization App Dynamic scheme

    Because of the dynamic things, I saw the source code of the implementation scheme for the first time , And I'm still a junior , I don't have much practical experience. Please forgive me for my mistakes , I also hope to point out that , Be informed of . After thinking about it for a long time, I decided to write it down , Please don't spray . And a friend of mine bestswifter ...

  8. Win7 System installation MySQL5.5.21 Illustrated tutorial

    from :http://www.jb51.net/article/37310.htm This article mainly introduces how to use win7 Install in mysql, So add MySQL Download process of , I hope it can help people in need Everybody knows M ...

  9. SQL View index

    View : A view is equivalent to a query result , It corresponds to the table surface ---- Where data is really stored View --- Don't store data , Show the results of the query Be careful : 1. Views are for the convenience of querying data . Generally, don't try to insert data into a view , It's easy to make mistakes . 2 ...

  10. Java Object comparator for generics List Sort -Demo

    For example : Field 1 Field 2 Field 3 Field n 1 hello 26 7891 world 89 5562 what 55 4562 the 85 452 fuck 55 995 haha 98 455 With ...