您的位置:首页 > 移动开发 > 微信开发

iOS 微信客服

2016-01-20 18:23 483 查看
到微信开发平台下载相关的SDK,添加到工程中;

在这里我直接入了机器人应答,你根据实际需求实现相关功能:

1.添加客服库文件:

1.添加库文件:libAppKeFuLib.a
2.添加资源文件:AppKeFuResources.bundle
3.添加头文件:AppKeFuLib.h

2.添加依赖库文件:

1、libxml2.dylib(或者Xcode7: libxml2.tbd)
2、libresolv.dylib(或者Xcode7: libresolv.tbd)
3、SystemConfiguration.framework
4、CoreLocation.framework
5、CoreData.framework
6、AVFoundation.framework
7、AudioToolbox.framework
8、libiconv.dylib(或者Xcode7: libiconv.tbd) (仅模拟器运行时需要)

3.Building Settings设置:

1. Other Linker Flags 添加 -all_load -lstdc++
注:或者使用 -force_load "libAppKeFuLib.a的路径" 代替-all_load,例如demo中:-force_load $(SRCROOT)/AppKeFuDemo2/AppKeFuLib/libAppKeFuLib.a
2(可选).Header Search Paths 添加 “/usr/include/libxml2”


在AppDelegate.h中实现方法:

//将demol中KFNavigationController文件加入到工程中
#import "AppDelegate.h"
#import "RootViewController.h"
#import "AppKeFuLib.h"
#import "KFNavigationController.h"

#define APP_KEY @"6f8103225b6ca0cfec048ecc8702dbce"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

//viewController必须要有一个试图控制器才可以,因为里面有个方法必须传一个试图控制器
RootViewController * rootVC = [[RootViewController alloc]init];
UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:rootVC];
self.window.rootViewController = nav;

[[AppKeFuLib sharedInstance] loginWithAppkey:APP_KEY];

//注册离线消息推送
//xcode 6
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

[application registerForRemoteNotifications];
} else {
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
//xcode 5
#else
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
#endif

return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

//同步deviceToken便于离线消息推送, 同时必须在管理后台上传 .pem文件才能生效
[[AppKeFuLib sharedInstance] uploadDeviceToken:deviceToken];

}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// 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.

//苹果官方规定除特定应用类型,如:音乐、VOIP类可以在后台运行,其他类型应用均不得在后台运行,所以在程序退到后台要执行logout登出,
//离线消息通过服务器推送可接收到
//在程序切换到前台时,执行重新登录,见applicationWillEnterForeground函数中
[[AppKeFuLib sharedInstance] logout];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
// 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.
//切换到前台重新登录
[[AppKeFuLib sharedInstance] loginWithAppkey:APP_KEY];
}


在RootViewController.m文件中实现方法:

//引入头文件
#import "RootViewController.h"
#import "AppKeFuLib.h"
#import "KFRightButtonItemCallBackTableViewController.h"

- (void)viewDidLoad {
[super viewDidLoad];

self.view.backgroundColor = [UIColor grayColor];
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100, 100);
btn.backgroundColor = [UIColor redColor];
[btn addTarget:self action:@selector(doClik) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

//监听登录状态
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(isConnected:) name:APPKEFU_LOGIN_SUCCEED_NOTIFICATION object:nil];

//监听在线状态
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(notifyOnlineStatus:) name:APPKEFU_WORKGROUP_ONLINESTATUS object:nil];

//监听接收到的消息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyMessage:) name:APPKEFU_NOTIFICATION_MESSAGE object:nil];

//监听连接服务器报错
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyXmppStreamDisconnectWithError:) name:APPKEFU_NOTIFICATION_DISCONNECT_WITH_ERROR object:nil];

}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];

[[NSNotificationCenter defaultCenter] removeObserver:self name:APPKEFU_LOGIN_SUCCEED_NOTIFICATION object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:APPKEFU_WORKGROUP_ONLINESTATUS object:self];
[[NSNotificationCenter defaultCenter] removeObserver:self name:APPKEFU_NOTIFICATION_MESSAGE object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:APPKEFU_NOTIFICATION_DISCONNECT_WITH_ERROR object:nil];
}
#pragma mark Login Succeed Notification
//接收是否登录成功通知
- (void)isConnected:(NSNotification*)notification
{
NSNumber *isConnected = [notification object];
if ([isConnected boolValue])
{
//登录成功
self.title = @"微客服3(登录成功)";

//
//查询工作组在线状态,需要将wgdemo替换为开发者自己的 “工作组名称”,请在官方管理后台申请,地址:http://appkefu.com/AppKeFu/admin
[[AppKeFuLib sharedInstance] queryWorkgroupOnlineStatus:@"wgdemo"];
[[AppKeFuLib sharedInstance] queryWorkgroupOnlineStatus:@"wgdemo2"];
}
else
{
//登录失败
self.title = @"微客服3(登录失败)";

}
}
#pragma mark OnlineStatus
//监听工作组在线状态
-(void)notifyOnlineStatus:(NSNotification *)notification
{
NSDictionary *dict = [notification userInfo];

//客服工作组名称
NSString *workgroupName = [dict objectForKey:@"workgroupname"];

//客服工作组在线状态
NSString *status   = [dict objectForKey:@"status"];

NSLog(@"%s workgroupName:%@, status:%@", __PRETTY_FUNCTION__, workgroupName, status);

//
if ([workgroupName isEqualToString:@"wgdemo"]) {

//        //客服工作组在线
//        if ([status isEqualToString:@"online"])
//        {
//            onlineStatus = NSLocalizedString(@"1.在线咨询售前(在线)", nil);
//        }
//        //客服工作组离线
//        else
//        {
//            onlineStatus = NSLocalizedString(@"1.在线咨询售前(离线)", nil);
//        }

}
//
else if ([workgroupName isEqualToString:@"wgdemo2"]) {

//        //客服工作组在线
//        if ([status isEqualToString:@"online"])
//        {
//            onlineStatus2 = NSLocalizedString(@"2.在线咨询售后(在线)", nil);
//        }
//        //客服工作组离线
//        else
//        {
//            onlineStatus2 = NSLocalizedString(@"2.在线咨询售后(离线)", nil);
//        }
}

}
#pragma mark Message

//接收到新消息
- (void)notifyMessage:(NSNotification *)nofication
{
NSLog(@"%s", __PRETTY_FUNCTION__);

KFMessageItem *msgItem = [nofication object];

//接收到来自客服的消息
if (!msgItem.isSendFromMe) {

//
NSLog(@"消息时间:%@, 工作组名称:%@, 发送消息用户名:%@",
msgItem.timestamp,
msgItem.workgroupName,
msgItem.username);

//文本消息
if (KFMessageTypeText == msgItem.messageType) {

NSLog(@"文本消息内容:%@", msgItem.messageContent);
}
//图片消息
else if (KFMessageTypeImageHTTPURL == msgItem.messageType)
{
NSLog(@"图片消息内容:%@", msgItem.messageContent);
}
//语音消息
else if (KFMessageTypeSoundHTTPURL == msgItem.messageType)
{
NSLog(@"语音消息内容:%@", msgItem.messageContent);
}

}

}
-(void)notifyXmppStreamDisconnectWithError:(NSNotification *)notification
{
//登录失败
self.title = @"微客服3(网络连接失败)";
}

#pragma mark BarButtonItem
-(void)leftBarButtonItemTouchUpInside:(UIButton *)sender
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)rightBarButtonItemTouchUpInside:(UIButton *)sender
{
NSLog(@"%s", __PRETTY_FUNCTION__);

KFRightButtonItemCallBackTableViewController *rightVC = [[KFRightButtonItemCallBackTableViewController alloc] init];
[self.navigationController pushViewController:rightVC animated:YES];
}
- (void)doClik
{

//自定义会话页面左上角返回按钮
UIButton *leftBarButtonItemButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 0, 60, 40)];
[leftBarButtonItemButton setTitle:@"返回" forState:UIControlStateNormal];
[leftBarButtonItemButton addTarget:self action:@selector(leftBarButtonItemTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];

//自定义会话界面titleView,如果不想自定义,请将对应参数设置为nill
UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
titleView.textColor = [UIColor greenColor];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.text = @"客服小秘书";

//自定义会话界面rightBarButtonItem,如果不想自定义,请将对应参数设置为nill
UIButton *rightBarButtonItemButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 0, 60, 40)];
[rightBarButtonItemButton setTitle:@"自定义" forState:UIControlStateNormal];
[rightBarButtonItemButton addTarget:self action:@selector(rightBarButtonItemTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];

//默认机器人应答,亦可呼叫人工客服
[[AppKeFuLib sharedInstance] pushChatViewController:self.navigationController
withWorkgroupName:@"wgdemo"
hideRightBarButtonItem:NO
rightBarButtonItemCallback:nil
showInputBarSwitchMenu:NO
withLeftBarButtonItem:leftBarButtonItemButton
withTitleView:titleView
withRightBarButtonItem:rightBarButtonItemButton
withProductInfo:nil
withLeftBarButtonItemColor:[UIColor whiteColor]
hidesBottomBarWhenPushed:FALSE
showHistoryMessage:FALSE
defaultRobot:TRUE
mustRate:FALSE
withKefuAvatarImage:[UIImage imageNamed:@"kefu_avatar"]
withUserAvatarImage:[UIImage imageNamed:@"user_avatar"]

shouldShowGoodsInfo:FALSE
withGoodsImageViewURL:nil
withGoodsTitleDetail:nil
withGoodsPrice:nil
withGoodsURL:nil
withGoodsCallbackID:nil
goodsInfoClickedCallback:nil

httpLinkURLClickedCallBack:^(NSString *url) {
NSLog(@"%@", url);
}
faqButtonTouchUpInsideCallback:nil];
}

/*
//参数的说明,根据实际需求来填写相对应的参数
-(void)presentKFCenterViewController:(UIViewController *)navController
withWorkgroupName:(NSString *)workgroupName
hidesBottomBarWhenPushed:(BOOL)shouldHide;

//4. 显示会话窗口
- (void)pushChatViewController:(UINavigationController *)navController
withWorkgroupName:(NSString *)workgroupName                        //1. 需要填写 工作组名称,需要到管理后台申请,
//   注意:不是客服用户名,而是工作组名称,支持多客服
hideRightBarButtonItem:(BOOL)hideRightBarButtonItem                     //2. 隐藏会话页面右上角按钮, 隐藏: YES, 显示: NO
rightBarButtonItemCallback:(void (^)())rightBarButtonTouchUpInsideCallback  //3. 会话页面右上角按钮回调函数;注意:VIP接口,需要另行开通
showInputBarSwitchMenu:(BOOL)shouldShowInputBarSwitchMenu               //4. 在会话窗口显示自定义菜单, 类似于微信的自定义菜单;
//      如果需要显示自定义菜单,请首先到管理后台分配自定义菜单,请分配且只分配三个自定义菜单,多于三个的自定义菜单将不予显示。
//      显示: YES, 不显示: NO
withLeftBarButtonItem:(UIButton *)leftBarButtonItem
withTitleView:(UILabel *)titleView                             //5. 自定义会话窗户标题
withRightBarButtonItem:(UIButton *)rightBarButtonItem                   //6. 自定义会话窗口右上角按钮,
//      如果需要保留默认, 请设置为nill
withProductInfo:(NSString *)productInfo                          //7. 成功连接客服之后,自动将此消息发送给客服,
//   如果不需要发送此信息, 可将其设置为 nil 或者 ""
withLeftBarButtonItemColor:(UIColor *)color                                 //8. 导航左上角“结束会话”按钮颜色
hidesBottomBarWhenPushed:(BOOL)shouldHide                                 //9. 从具有Tabbar的viewController打开的时候,隐藏tabbar
showHistoryMessage:(BOOL)isShow                                     //10. 是否显示历史聊天记录,显示:YES, 不显示:NO
defaultRobot:(BOOL)defaultRobot                               //11. 默认机器人自动应答, 亦可呼叫人工客服,
//   开启机器人: YES, 人工客服: NO
mustRate:(BOOL)mustRate                                   //12.在关闭会话的时候是否强制用户评价,强制:YES, 不评价:NO
//   注意:如果要强制用户在关闭会话的时候评价,需要首先设置参数:
//      withLeftBarButtonItem,否则此参数不会生效
withKefuAvatarImage:(UIImage *)kefuAvatarImage                       //13. 替换默认客服头像, 设为nil则保留默认头像
withUserAvatarImage:(UIImage *)userAvatarImage                       //14. 替换默认用户头像, 设为nil则保留默认头像

shouldShowGoodsInfo:(BOOL)showGoodsInfo                              //15.是否显示商品信息,
//      取值:true,显示商品信息; false,不显示商品信息
withGoodsImageViewURL:(NSString *)goodsImageViewURL                    //16.商品信息图片URL链接地址
withGoodsTitleDetail:(NSString *)goodsTitleDetail                     //17.商品信息简介
withGoodsPrice:(NSString *)goodsPrice                           //18.商品价格
withGoodsURL:(NSString *)goodsURL                             //19.商品链接,点击“发送链接”按钮发送给客服
withGoodsCallbackID:(NSString *)goodsCallbackID                      //20.点击商品区域回调参数
goodsInfoClickedCallback:(void (^)(NSString *goodsCallbackId))goodsInfoClickedCallback //21.点击商品区域回调接口

httpLinkURLClickedCallBack:(void (^)(NSString *url))httpLinkURLClickedCallback //22.点击URL的回调函数,如果不想使用回调,请设置为nil
faqButtonTouchUpInsideCallback:(void (^)())faqButtonTouchUpInsideCallback;      //23.自定义FAQ常见问题button回调,可在此打开自己的常见问题FAQ页面

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: