网络编程
根据极客班iOS课程整理。
一. 创建网络连接
1. 声明实现代理
@interface LoginRequest()<NSURLConnectionDataDelegate>
@end
2. 创建网络链接
NSString *URLString = @"http://urlAddress/login.json";
URLString = [NSString stringWithFormat:@"%@?username=%@&password=%@", URLString,username, password];
// 给字符串编码为utf-8, 否则中文字符会"unsupported URL"
NSString *encodedURLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:encodedURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"GET";
request.timeoutInterval = 60; //设置超时
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
self.URLConnection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
3. 实现代理
3.1 获取连接状态,“statusCode == 200”表示成功
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) { //success
self.receivedData = [NSMutableData data];
} else {
// error methods
}
}
3.2 从服务器获取数据
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data
{
[self.receivedData appendData:data];
}
3.3 加载完数据
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *string = [[NSString alloc] initWithData:self.receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
}
3.4 出错
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
4. 网络请求
4.1 同步请求
[NSURLConnection sendSynchronousRequest:<#(NSURLRequest *)#>
returningResponse:<#(NSURLResponse *__autoreleasing *)#>
error:<#(NSError *__autoreleasing *)#>];
4.2 异步请求(默认)
[NSURLConnection sendAsynchronousRequest:<#(NSURLRequest *)#>
queue:<#(NSOperationQueue *)#>
completionHandler:<#^(NSURLResponse *response, NSData *data, NSError *connectionError)handler#>
二. 解析数据
1. JSON (Java Script Object Notation)
apple提供了函数
id jsonDic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
注意:
- value不一定是string,使用时需要判断
if ([[userId class] isSubclassOfClass:[NSString class]]) {
user.userID = userId;
}
2. XML
2.1 解析方式
- SAX,遍历,
apple支持
,需要实现代理 - DOM,先把数据转换成树
- TBXML,开源库
2.2 声明实现XML代理
<NSXMLParserDelegate>
2.3 实现代理方法
1.开始节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
2.结束节点
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
3.数据
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
4.解析xml数据
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
NSError *error = [parser parserError];
if (error) {
...
} else {
...
parser.delegate = self;
[parser parse]; // 开始解析
...
}
2.4 节点重名的处理
<?xml version="1.0" encoding="UTF-8" ?>
<user>
<id><![CDATA[00001]]></id>
<userName>zhangsan</userName>
<age>28</age>
<headImageUrl>http://pica.nipic.com/2007-11-09/2007119124413448_2.jpg</headImageUrl>
<address>
<id>12345</id>
<city>上海</city>
</address>
</user>
如上,"id"有两个。发生这种情况的时候,需要由內向外
进行处理。
在didStartElement代理方法中添加:
if ([elementName isEqualToString:@"address"]) {
_address = [[BLAddress alloc] init];
}
在didEndElement代理方法中添加
if ([elementName isEqualToString:@"address"]) {
_user.address = _address;
_address = nil;
} else if ([elementName isEqualToString:@"id"]) {
if (_address) {
_address.cityID = _currentValue;
} else {
_user.userID = _currentValue;
}
在address节点之间发现“id”时,_address不是空的。而在address节点之外,_address是空的。根据_address是否为空就能判断当前应给哪个id赋值。
三. 全局变量
3.1 创建全局类
@interface BLGlobal : NSObject
@property (nonatomic, strong) BLUser *user;
+ (BLGlobal *)shareGlobal;
@end
实现
static BLGlobal *global = nil;
@implementation BLGlobal
+ (BLGlobal *)shareGlobal
{
if (global == nil) {
global = [[BLGlobal alloc] init];
}
return global;
}
3.2 访问
[BLGlobal shareGlobal].user
3.3 其他
- XXFoundation.h, 存放宏定义、枚举等