天天看點

智能聊天機器人實作(源代碼+解析)

前言:

之前寫了一篇  ​《美女圖檔採集器 (源代碼+解析)》 得到了衆多朋友的支援, 發現這樣系列的教程還是挺受歡迎的, 也激勵我繼續寫下去。

也在那一篇文章中提過, 美女圖檔採集僅僅是我先前那個完整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];
}      

學習的路上, 與君共勉