前言:
之前寫了一篇 《美女圖片採集器 (源代碼+解析)》 得到了眾多朋友的支持, 發現這樣系列的教程還是挺受歡迎的, 也激勵我繼續寫下去。
也在那一篇文章中提過, 美女圖片採集僅僅是我先前那個完整APP中的一個功能罷了, 還有其它幾個比較好玩的尚未開源, 之后有時間會逐一寫篇教程。
今天帶來的是智能聊天機器人實現(源代碼+解析), 和上一篇教程一樣, 當你沒有女朋友的時候, 能夠用它來打發時間。
這里的API是圖靈機器人提供的, 實現一個十分強大的機器人。
詳細功能包含:
• 支持聊天對話、智能問答
• 擁有笑話、天氣、公交等豐富功能
• 支持自然語言處理及語義理解
• 數十億知識庫數據,應有盡有
執行效果:
源代碼下載:
源代碼已經傳到git上了, 歡迎下載學習。
下載鏈接: https://github.com/colin1994/tulingIOS
源代碼解析:
一。仿微信界面
這個小demo的界面是仿微信的。僅僅只是是簡化版的, 包含表情, 語音什么的, 都省略了。
對於界面這一塊, 我這里不多做介紹, 由於這並非本教程主要內容。畢竟, 這個界面到自己實際項目中的時候, 肯定是須要自己定義的。
這里簡要介紹一下。
該界面分成兩部分:
1. UITableView: 顯示聊天列表, 當中, 左邊的是機器人回答, 右邊是自己的提問。
另外, 列表的每一個cell, 由頭像和文字組成。 這個cell是自己定義的, 詳細能夠自己查看源代碼。
列表加入:
//add UItableView self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-88) style:UITableViewStylePlain]; [self.tableView registerClass:[ChartCell class] forCellReuseIdentifier:cellIdentifier]; self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone; self.tableView.allowsSelection = NO; self.tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chat_bg_default.jpg"]]; self.tableView.dataSource=self; self.tableView.delegate=self; [self.view addSubview:self.tableView];
2. KeyBordVIew: 自己定義的UIView, 用來顯示自己定義的鍵盤視圖。
鍵盤加入:
//add keyBorad self.keyBordView=[[KeyBordVIew alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-44, self.view.frame.size.width, 44)]; self.keyBordView.delegate=self; [self.view addSubview:self.keyBordView];
另外, 鍵盤涉及彈出和收起操作操作, 這個須要在視圖加載之前, 注冊通知, 響應相關操作。
1.注冊通知
//注冊通知, 鍵盤收起, 彈出 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
2.響應操作
//鍵盤彈出響應 -(void)keyboardShow:(NSNotification *)note { CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGFloat deltaY=keyBoardRect.size.height; [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{ self.view.transform=CGAffineTransformMakeTranslation(0, -deltaY); }]; } //鍵盤收起響應 -(void)keyboardHide:(NSNotification *)note { [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{ self.view.transform = CGAffineTransformIdentity; }]; }
二。
圖靈key獲取
用過一些第三方API的都知道, 通常我須要先注冊成為它的用戶, 才干獲取相應的key, 以便調用API。
圖靈也不例外, 你須要先注冊成為圖靈用戶, 然后有相關教程, 教你怎樣獲取自己的key, 以及正確的URL。這里就不反復了。圖靈機器人官網鏈接
比如, 我這個demo里面的key是:6c2cfaf7a7f088e843b550b0c5b89c26
相應的API是:http://www.tuling123.com/openapi/api?key=6c2cfaf7a7f088e843b550b0c5b89c26&&info=%@
所以, 你僅僅要把這里的key替換成你自己的就能夠了。
三。圖靈API的使用
這里使用了第三方網絡請求庫ASI 和 json格式數據解析庫 JsonKit。
在導入ASI的時候, 假設你的項目是ARC, 那么, 請將相應的文件設置成支持ARC就可以。 (-fno-objc-arc)
另外, 要導入一些框架
SystemConfiguration.framework
MobileCoreServices.framework
CFNetwork.framework
libz.dylib
接着就能利用ASI調用圖靈API,再利用jsonkit解析返回的數據了。
詳細實現例如以下:
//每當編輯完問題后 //1. 顯示自己的問題 messageType=1 //2. 調用API,返回結果 -(void)KeyBordView:(KeyBordVIew *)keyBoardView textFiledReturn:(UITextField *)textFiled { //顯示自己的問題 ChartCellFrame *cellFrame=[[ChartCellFrame alloc]init]; ChartMessage *chartMessage=[[ChartMessage alloc]init]; chartMessage.icon=@"icon01.png"; chartMessage.messageType=1; chartMessage.content=textFiled.text; cellFrame.chartMessage=chartMessage; [self.cellFrames addObject:cellFrame]; [self.tableView reloadData]; //滾動到當前行 [self tableViewScrollCurrentIndexPath]; //利用用戶問題, 查詢結果 //API請求格式。 詳細格式見圖靈官網 //6c2cfaf7a7f088e843b550b0c5b89c26 替換成你申請的key就可以 NSString* urlString = [NSString stringWithFormat:@"http://www.tuling123.com/openapi/api?key=6c2cfaf7a7f088e843b550b0c5b89c26&&info=%@", textFiled.text]; //NSUTF8StringEncoding編碼。
避免中文錯誤 urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //調用API NSURL *url = [NSURL URLWithString:urlString]; testRequest = [ASIHTTPRequest requestWithURL:url]; [testRequest setDelegate:self]; [testRequest startAsynchronous]; textFiled.text=@""; myTextField = textFiled; } #pragma mark - 返回機器人回答 //調用API完成, 返回圖靈回答結果 //1. 收起鍵盤 //2. 顯示回答內容 - (void)requestFinished:(ASIHTTPRequest *)request { //收起鍵盤 [myTextField resignFirstResponder]; // 當以文本形式讀取返回內容時用這種方法 // 解析返回的json數據 NSString *responseString = [request responseString]; self.testDic = [responseString objectFromJSONString]; self.testArr = [testDic objectForKey:@"text"]; //顯示回答內容 ChartCellFrame *cellFrame=[[ChartCellFrame alloc]init]; ChartMessage *chartMessage=[[ChartMessage alloc]init]; chartMessage.icon=@"icon02.png"; chartMessage.messageType=0; chartMessage.content=[NSString stringWithFormat:@"%@", self.testArr]; cellFrame.chartMessage=chartMessage; [self.cellFrames addObject:cellFrame]; [self.tableView reloadData]; //滾動到當前行 [self tableViewScrollCurrentIndexPath]; } // API請求失敗 - (void)requestFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; NSLog(@"error --- %@",error); UIAlertView *alert_ = [[UIAlertView alloc]initWithTitle:@"提示" message:@"無網絡可用,請檢查網絡狀態" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil]; [alert_ show]; }