Integrated huanxin SDK and applesdk for Apple Watch

Source: Internet
Author: User

Integrated huanxin SDK and applesdk for Apple Watch

This article briefly describes how to integrate the huanxin SDK with Apple Watch Kit.

Upgrade xcode to version 6.2 and IOS SDK8.2

Download the huanxin SDK from the official website

Choose XCode> new project> new target> WatchKit App.


Xcode will automatically create several targets for you, for example:


Drag the EaseMobSDK folder to HxAppleWatchDemo Target.


Select target HXAppleWatchDemo and add the library files in all Linked Frameworks and Libraries.


Create a bridging header file in HXAppleWatchDemo target


Set the bridging header file


Set other linker flags to ensure that the SDK Lib category extension method is available.


All environment settings have been completed. Are you sure you want to build it?

Start to write the code:

1. Open the interface. storyboard in the HXAppleWatchDemo WatchKit App and add a button called load contacts.


2. Find the InterfaceController. swift file in HXAppleWatchDemo WatchKit Extension, and then associate the button

@ IBOutlet weakvar open: WKInterfaceButton!

The InterfaceController. swift code is as follows:

//// InterfaceController. swift // HXAppleWatchDemo WatchKit Extension // Created by youni on 15/4/1. // Copyright (c) 2015 youni. all rights reserved. // import WatchKitimport Foundationclass InterfaceController: WKInterfaceController {@ IBOutlet weak var open: WKInterfaceButton! @ IBAction func openApp () {InterfaceController. openParentApplication (["action": "getcontact"], reply: {(info: [NSObject: AnyObject]!, Error: NSError !) -> Void in if info! = Nil {if info. count> 0 {self. getContacts (info! ["Contacts"] as [String]) }})} func getContacts (contacts: [String]) {presentTextInputControllerWithSuggestions (contacts, allowedInputMode: WKTextInputMode. plain, completion: {(result: [AnyObject]!) -> Void in if result! = Nil {var id: String = result [0] as String var date: NSDate = NSDate () var now: NSTimeInterval = date. timeIntervalSinceNow self. sendMessage (id, text: now. description) }}func sendMessage (id: String, text: String) {InterfaceController. openParentApplication (["action": "send", "name": id, "message": text], reply: {(info: [NSObject: AnyObject]!, Error: NSError !) -> Void in})} override func awakeWithContext (context: AnyObject ?) {Super. awakeWithContext (context) // Configure interface objects here .} override func willActivate () {// This method is called when watch view controller is about to be visible to user super. willActivate ()} override func didDeactivate () {// This method is called when watch view controller is no longer visible super. didDeactivate ()}}

InterfaceController. openParentApplication is an interface used to communicate with IOS programs. Most of the business logic needs to be implemented in the parent application, that is, HXAppleWatchDemo Target.

Let's take a look at how HXAppleWatchDemo communicates with the Apple Watch App.

//// AppDelegate. swift // HXAppleWatchDemo /// Created by youni on 15/4/1. // Copyright (c) 2015 youni. all rights reserved. // import UIKit @ UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate, IChatManagerDelegate {var window: UIWindow? Var callback :( ([NSObject: AnyObject]!) -> Void )! Func application (application: UIApplication, didfinishlaunchingwitexceptions launchOptions: [NSObject: AnyObject]?) -> Bool {// Override point for customization after application launch. let apnsCertName: String = "chatdemoui"; EaseMob. sharedInstance (). registerSDKWithAppKey ("easemob-demo # chatdemoui", apnsCertName: apnsCertName) EaseMob. sharedInstance (). chatManager. addDelegate (self, delegateQueue: nil) EaseMob. sharedInstance (). chatManager. asyncLoginWithUsername ("tt1", password: "1", completion: {(loginInfo, erro R)-> Void in NSLog ("login callback:") HXSDKHelper. instance. sendTextMessage ("uni3", textMessge: "test from")}, onQueue: nil) return true} func applicationWillResignActive (application: UIApplication) {// Sent when the application is about to move from active to inactive state. this can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when User quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. games shocould use this method to pause the game .} func applicationDidEnterBackground (application: UIApplication) {// Use this method to release shared resources, save user data, invalidate timers, and store enough app Lication state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits .} func applicationWillEnterForeground (application: UIApplication) {// Called as part of the transition from the background to the inactive state; here you ca N undo records of the changes made on entering the background .} func applicationDidBecomeActive (application: UIApplication) {// Restart any tasks that were paused (or not yet started) while the application was inactive. if the application was previusly in the background, optionally refresh the user interface .} func applicationWillTerminate (application: UIApplication) {// Called when the applicat Ion is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.} func application (application: UIApplication !, HandleWatchKitExtensionRequest userInfo: [NSObject: AnyObject]!, Reply: ([NSObject: AnyObject]!) -> Void )!) {If (userInfo! = Nil) {if userInfo! ["Action"]! = Nil {var action: String = userInfo! ["Action"] as String if action = "getcontact" {reply! (["Contacts": ["uni3", "uni5", "tt2"])} else if action = "send" {var name: String = userInfo! ["Name"] as String var message: String = userInfo! ["Message"] as String NSLog ("name:" + name + "message:" + message) HXSDKHelper. instance. sendTextMessage (name, textMessge: message) callback = reply }}} func didSendMessage (message: EMMessage !, Error: EMError !) {If (error! = Nil) {callback! (["Send": error !. ErrorCode. value])} else {callback! (["Send": "OK"])} func didReceiveMessage (message: EMMessage !) {}}
This is the interface for communication with the Apple WatchKit App:
func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {                if(userInfo != nil){            if userInfo!["action"] != nil{                var action:String = userInfo!["action"] as String                                if action == "getcontact"{                    reply!(["contacts":["uni3","uni5","tt2"]])                }else if action == "send"{                    var name:String = userInfo!["name"] as String                    var message:String = userInfo!["message"] as String                    NSLog("name : " + name + "message : " + message)                    HXSDKHelper.instance.sendTextMessage(name, textMessge:message)                    callback = reply                }            }        }    }

HXSDKHelper is a simple encapsulation of huanxin, which only implements one function.

//// HXSDKHelper. swift // swittest /// Created by youni on 15/3/15. // Copyright (c) 2015 youni. all rights reserved. // import Foundationprivate var gInstance = HXSDKHelper () class HXSDKHelper: NSObject {class var instance: HXSDKHelper {return gInstance} func sendTextMessage (to: String, textMessge: String) {var latestMessage: EMMessage = EMMessage () var chatText: EMChatText = EMChatText (text: textMessge) var txtBody: EMTextMessageBody = EMTextMessageBody (chatObject: chatText) latestMessage. addMessageBody (txtBody); latestMessage. to = to; EaseMob. sharedInstance (). chatManager. asyncSendMessage (latestMessage, progress: nil );}}

After completing the above steps, you can make a simple Watch App to send messages using the ring mail SDK.

Since there is no real machine, all of the above are tested on the simulator.

If you need engineering code, contact me: syyorient@outlook.com

Or get it from github.

Https://github.com/youniworld/AppleWatchDemo-HuanXin


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.