本文简单的讲述下怎样用Apple Watch Kit集成环信SDK.

升级xcode到version 6.2,和 IOS SDK8.2

下载环信SDK从官网

打开XCode->new project->new target->选择WatchKit App

xcode 会自己主动给你创建几个targets,比例如以下图:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW91bml3b3JsZA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

把EaseMobSDK目录拖拽到HxAppleWatchDemo Target里

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW91bml3b3JsZA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

选择target HXAppleWatchDemo,增加下图全部的Linked Frameworks and Libraries里的库文件

在HXAppleWatchDemo target 创建bridging header文件

设置bridging header文件

设置other linker flags 以保证SDK Lib category的扩展方法可用

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW91bml3b3JsZA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

全部环境设置都已完毕,试着build下看又啥问题么

開始写代码:

1. 打开HXAppleWatchDemo WatchKit App 里的interface.storyboard然后加个button 叫load contacts

2. 找到HXAppleWatchDemo WatchKit Extension里的文件InterfaceController.swift,然后把上述的button关联到

@IBOutlet weakvar open:WKInterfaceButton!

InterfaceController.swift代码例如以下

//
// InterfaceController.swift
// HXAppleWatchDemo WatchKit Extension
//
// Created by youni on 15/4/1.
// Copyright (c) 2015年 youni. All rights reserved.
// import WatchKit
import Foundation class 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是用来和IOS的程序通讯的接口,大部分的业务逻辑须要在parent application实现也就是上述说的HXAppleWatchDemo Target

我们看下HXAppleWatchDemo是怎样实现和Apple Watch App通讯的

//
// AppDelegate.swift
// HXAppleWatchDemo
//
// Created by youni on 15/4/1.
// Copyright (c) 2015年 youni. All rights reserved.
// import UIKit @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,IChatManagerDelegate{ var window: UIWindow? var callback:(([NSObject : AnyObject]!) -> Void)! func application(application: UIApplication, didFinishLaunchingWithOptions 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,error) -> 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 the 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 should 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 application 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 can undo many 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 previously in the background, optionally refresh the user interface.
} func applicationWillTerminate(application: UIApplication) {
// Called when the application 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!) { }
}

这个就是和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就是对环信一个简单的封装,如今里面仅仅实现了一个函数

//
// HXSDKHelper.swift
// swittest
//
// Created by youni on 15/3/15.
// Copyright (c) 2015年 youni. All rights reserved.
// import Foundation private 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);
}
}

大功告成。完毕以上步骤,你就行做个简单的Watch App 可以用环信的SDK发消息了。

因为没有真机,以上都是在模拟器上測试通过。

假设须要project代码请联系我:syyorient@outlook.com

或者从github上获取

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

Apple Watch 集成环信SDK的更多相关文章

  1. [iOS]集成环信SDK然后运行时候crash了-[NSBundle initWithURL:]: nil URL argument'

    Crash的reason是-[NSBundle initWithURL:]: nil URL argument' 1.首先我是用cocoapods导入的环信的SDK.然后怎么运行怎么crash. 2. ...

  2. 李洪强iOS开发本人集成环信的经验总结_01环信SDK的导入

    李洪强iOS开发本人集成环信的经验总结_01环信SDK的导入 01 - 直接在项目中导入SDK和一些静态库 这个时候,没有错误的编译没有错误的话,就说明SDK已经配置成功 还有一种方法是用cocoap ...

  3. iOS:集成环信EaseMobSDK单聊功能

    当然在集成环信之前需要一些准备操作: 1.首先注册环信开发者账号,直接进入环信官网注册即可:http://www.easemob.com 2.按照文档一步一步将需要的文件全部拖入工程中:http:// ...

  4. Android 使用easeui 3.0 集成环信即时通讯 我踩过的坑

    0.关于注冊账号就不用说了. 1.创建应用.获取appkey 0.创建应用 1.填写信息 2.获取appkey 2.集成 0.首先新建一个project 1.这里主要介绍使用easeui来集成环信的即 ...

  5. 集成环信时遇到的问题file not found: libEaseMobClientSDK.a

    集成环信时遇到的问题 build setting环信SDK集成libEaseMobClientSDKL  file not found: libEaseMobClientSDK.a clang: er ...

  6. 李洪强iOS开发本人集成环信的经验总结_09_处理好友请求

    李洪强iOS开发本人集成环信的经验总结_09_处理好友请求 实现这种效果: 01 - 遵守处理好友请求的代理协议 02  - 设置代理 03 - 实现代理方法 04 - 实现代理中用到的方法 

  7. 李洪强iOS开发本人集成环信的经验总结_08_自动登录补充

    李洪强iOS开发本人集成环信的经验总结_08_自动登录补充 来到Appdelegate里面 01 - 遵守自动登录的代理协议 02 - 设置自动登录的代理 03 - 判断与实现  04 - 代理方法的 ...

  8. 李洪强iOS开发本人集成环信的经验总结_07_监听好友请求

    李洪强iOS开发本人集成环信的经验总结_07_监听好友请求 来到Appdalegate中: 遵守代理协议 设置代理  实现监听好友请求的回调的方法

  9. 李洪强iOS开发本人集成环信的经验总结_06_发送好友请求

    李洪强iOS开发本人集成环信的经验总结_06_发送好友请求 同步好友请求 异步好友请求

随机推荐

  1. Magento--修改已存在的订单的运费

    遇到一种情况,需要在下单后再由管理员添加订单运费,然后顾客再付款.那么问题来了,如何给订单添加运费呢?下面是一段代码,可以实现该功能: $orderId = 'your order id';$orde ...

  2. Windows Server8下补丁分发配置与iSCSI配置

    1.Win Server 8 下配置补丁分发(高清视频下载:http://down.51cto.com/data/424305)本视频适合于Windows Server系统管理员学习 650) thi ...

  3. 实现人脸识别性别之路---matplotlib

    Np.linspace(start,stop,num,endpoint,dtype)函数 1.参数:范围值,在范围值中取到的数值总数.是否包含范围值.类型 2.返回值:返回一维数据 3.在指定的范围内 ...

  4. tee---将数据重定向到文件,

    tee命令用于将数据重定向到文件,另一方面还可以提供一份重定向数据的副本作为后续命令的stdin.简单的说就是把数据重定向到给定文件和屏幕上. 存在缓存机制,每1024个字节将输出一次.若从管道接收输 ...

  5. Linux学习总结(6)——CenterOS7安装mysql5.5的方法

    首先centos7 已经不支持mysql,因为收费了你懂得,所以内部集成了mariadb,而安装mysql的话会和mariadb的文件冲突,所以需要先卸载掉mariadb,以下为卸载mariadb,安 ...

  6. Windows server 2016 解决“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同。”

    使用克隆的系统时,加域是出现如下问题.“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同.” 问题原因:Windows使用SID来表示所有的安全对象(security principa ...

  7. Linux中为XEN网桥绑定物理网卡

    XEN虚拟机会默认将可以连通外网的网卡绑定到xenbr0上, 因此如果需要切换到其他物理网卡上时,需要自己配置脚本或执行命令. 1.添加脚本绑定 a.编写一个脚本,指定网卡与网桥绑定的关系 # vim ...

  8. LintCode 二叉树的遍历 (非递归)

    前序: class Solution { public: /** * @param root: The root of binary tree. * @return: Preorder in vect ...

  9. hdoj-1593-find a way to escape【数学题】

    find a way to escape Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...

  10. Codeforces 472D

    看官方题解提供的是最小生成树,怎么也想不明确.you can guess and prove it! 看了好几个人的代码.感觉实现思路全都不一样,不得不佩服cf题目想法的多样性 以下说说我自己的理解, ...