想要實現異步獲取的話我這邊了解過來有兩個非常簡單的方式
一個是利用ASIHTTPRequest來實現異步獲取數據
另一個則是利用MBProgressHUD來實現異步獲取數據
本章就先來講解如何利用ASIHTTPRequest類來實現異步數據獲取
首先大家需要百度一下ASIHTTPRequest 然后看一下百度里搜到的那些文章(不要問具體是那篇,因為我發現百度搜過來的東西全部都是一樣的,所以。。。。大致看下 哪篇都一樣的就知道我說的是哪篇了,這也是為什么我決定自己寫點內容的原因。再次吐槽百度個坑爹的家伙。)
看完了的話就接着看我們的內容吧
需要添加的類庫
CFNetwork.framework ,SystemConfiguration.framework, MobileCoreServices.framework,CoreGraphics.framework和libz.1.2.3.dylib
我就直接上代碼了我這邊使用的是ASIFormDataRequest,使用前需要引用頭文件 ASIFormDataRequest.h
我這邊在GetWebInfo類里面定義了一個nsstring 類型的mywebaddress屬性用來存放地址,這樣的話可以便於我們管理地址
#pragma mark #pragma 異步加載數據 //初始化數據 異步加載 -(void)initListData{ // NSURL *url=[NSURL URLWithString:@"http://xxx.xxx.xxx.xxx/WebServicesForIOS/IOSWebservices.ashx?Method=GetNewsbyPage&type=公共新聞&rows=4&page=1"]; GetWebInfo *getwebinfo=[[GetWebInfo alloc] init]; NSURL *url=[NSURL URLWithString:getwebinfo.mywebaddress]; ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url]; NSString *mypage=[NSString stringWithFormat:@"%d",_page ]; [request addPostValue:@"GetNewsbyPage" forKey:@"Method"]; [request addPostValue:@"公共新聞" forKey:@"type"]; [request addPostValue:@"4" forKey:@"rows"]; [request addPostValue:mypage forKey:@"page"]; [request setDelegate:self]; [request startAsynchronous]; } //異步加載成功 - (void)requestFinished:(ASIHTTPRequest *)request { NSData *responseData = [request responseData]; NSArray *keys = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; allcount=[[keys valueForKey:@"total"] integerValue]; [self.list addObject:[keys valueForKey:@"rows"]]; [_tableView reloadData]; } //異步加載失敗 - (void)requestFailed:(ASIHTTPRequest *)request { // NSError *error = [request error]; UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示信息!" message:@"加載數據失敗!網絡連接失敗!" delegate:Nil cancelButtonTitle:@"確定" otherButtonTitles: nil]; [alert show]; }
代碼就是這么簡單,一個是異步獲取失敗方法,一個是異步獲取成功方法。。。。
然后就沒有然后了。。。。就是這么的簡單。
OK本章內容非常少,但是。。。卻會很使用,然后。。真的就是這么簡單。。
下一章會介紹如何利用 MBProgressHUD 進行異步獲取數據。。那個。。更加的簡單。