无线客户端框架设计(5):调用MobileAPI的设计(iOS篇)

移动开发 iOS
本文将为您讲述如何发起网络请求,iOS用于调用MobileAPI的第三方组件很多。我们会在后续的章节,介绍Cookie的处理和时间校准机制,它们都和调用MobileAPI息息相关。

这一节讲如何发起网络请求。

iOS用于调用MobileAPI的第三方组件很多,我们这里采用的是以下组件:

1)ASIHTTPRequest,用于请求MobileAPI:http://allseeing-i.com/ASIHTTPRequest/ 

 iOS教程之ASIHttpRequest完全攻略

2)SBJson,2.3版本,用于解析JSON:http://stig.github.com/json-framework/

由于我们在MyLib中引用了SBJson,它里面有一个Category名为NSString+SBJSON,为了能使用它,请在

MyLib和MyApp项目中的Other Linker Falgs设为-all_load。

这一节内容非常芜杂,我将其分为以下几个部分:

1)将返回JSON格式的数据转换实体类

2)网络请求的封装——汇总API的配置文件

3)网络请求的封装——RemotingService横空出世

4)网络请求的封装——一些善后工作

5)数据缓存

6)自动重试

7)自动化实体生成器

此外,我们会在后续的章节,介绍Cookie的处理和时间校准机制,它们都和调用MobileAPI息息相关。

本文采取的例子是开源免费天气预报接口API以及全国所有地区代码!!(国家气象局提供):http://mobile.51cto.com/hot-409995.htm

先给出一个ASIHTTPRequest+SBJson的例子:YoungHeart-Chapter-05.zip

关键代码如下所示:

  1. - (void)loadData { 
  2.     NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/sk/101010100.html"]; 
  3.     ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
  4.     [request setDelegate:self];     
  5.     [request startAsynchronous]; 
  6.  
  7. - (void)requestFinished:(ASIHTTPRequest *)request { 
  8.     NSString *jsonStr  =[request responseString]; 
  9.      
  10.     SBJsonParser *jsonParser = [[SBJsonParser alloc] init]; 
  11.      
  12.     NSMutableDictionary *dict = [jsonParser objectWithString:jsonStr]; 
  13.     NSLog(@"%@",dict); 
  14.      
  15.     [jsonParser release]; 
  16.     id jsonValue = [jsonStr JSONValue]; 
  17.  
  18. - (void)requestFailed:(ASIHTTPRequest *)request { 
  19.     UIAlertView* alertView = [[UIAlertView alloc]initWithTitle: @"粗锉啦" message: @"Network Error" delegate: self cancelButtonTitle: @"OK" otherButtonTitles: nil]; 
  20.     [alertView show]; 
  21.     [alertView release]; 

 

责任编辑:闫佳明 来源: cnblogs
相关推荐

2013-09-03 09:35:48

无线客户端框架设计iOS

2013-09-03 09:55:42

iOS无线客户端框架设计

2013-09-09 10:36:14

iOS无线客户端框架设计

2013-09-16 10:43:15

无线客户端框架设计iOSJSON

2013-09-03 09:10:56

2011-03-07 13:50:20

2013-03-14 10:12:54

视觉设计产品设计

2012-06-25 12:43:26

.NET框架

2012-11-28 11:05:42

IBMdW

2023-03-31 13:31:45

2020-07-30 10:35:32

Java反射框架设计

2012-01-18 10:20:42

框架设计

2009-06-12 19:18:08

REST客户端框架JavaScript

2012-06-25 09:28:42

.NET可逆框架

2009-09-16 16:09:41

NIS服务器客户端NIS

2012-02-10 10:27:54

WLANVDI

2011-07-07 13:21:56

UI设计

2014-03-10 10:22:40

JavaScriptJS弊端

2010-07-14 11:08:48

调用SQL Serve

2009-09-08 09:12:12

LINQ构建框架设计
点赞
收藏

51CTO技术栈公众号