網絡編程
根據極客班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, 存放宏定義、枚舉等