http網(wǎng)絡(luò)庫是集XML解析,Json解析撼班,網(wǎng)絡(luò)圖片下載歧匈,plist解析,數(shù)據(jù)流請(qǐng)求操作砰嘁,上傳件炉,下載,緩存等網(wǎng)絡(luò)眾多功能于一身的強(qiáng)大的類庫矮湘。最新版本支持session斟冕,xctool單元測(cè)試。網(wǎng)絡(luò)獲取數(shù)據(jù)一直是手機(jī)軟件的重中之重缅阳,如果處理的不好磕蛇,會(huì)造成很差的用戶體驗(yàn)。隨著ASIHTTPRequest的停止更新,更換網(wǎng)絡(luò)庫是必然的事情秀撇,AFNetworking就是很好的替代品超棺。而且都是輕量級(jí),不要擔(dān)心加入太多庫會(huì)多軟件性能有影響呵燕。
1.為什么用第三方網(wǎng)絡(luò)庫棠绘?先說如果不用網(wǎng)絡(luò)庫,我曾有一次覺得什么都用蘋果原生的好再扭,XML解析用蘋果自帶的委托氧苍,下載圖片自己寫,如果你也有跟我一樣的經(jīng)歷泛范,那你會(huì)發(fā)現(xiàn)自己管理起來很復(fù)雜让虐,很容易出錯(cuò)。而且性能不好敦跌。如果你是一個(gè)追求完美的人澄干,那就放下你的固執(zhí)逛揩,就如當(dāng)初的我一樣柠傍,嘗試一下網(wǎng)絡(luò)庫吧。
2.為什么要用AFNetworking?第一點(diǎn)辩稽,它有人更新和維護(hù)惧笛,而且目前使用者很多,第二點(diǎn)逞泄,還是使用者很多患整,那么他的資料,文檔喷众,demo就多各谚,很好找遇到問題好解決。如果不用AFNetworking到千,還有一種MKNetworkKit也不錯(cuò)昌渤,不妨一試。
***
## 如何通過URL獲取json數(shù)據(jù)
第一種憔四,利用AFJSONRequestOperation膀息,官方網(wǎng)站上給的例子:
```js
NSString*str=[NSStringstringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL*url = [NSURL URLWithString:[strstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
//從URL獲取json數(shù)據(jù)
AFJSONRequestOperation*operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestsuccess:^(NSURLRequest*request,NSHTTPURLResponse*response,NSDictionary* JSON) {
NSLog(@"獲取到的數(shù)據(jù)為:%@",JSON);
}failure:^(NSURLRequest*request,NSHTTPURLResponse*response,NSError*error,iddata) {
NSLog(@"發(fā)生錯(cuò)誤!%@",error);
}];
[operation1start];
```
***
第二種方法了赵,利用AFHTTPRequestOperation 先獲取到字符串形式的數(shù)據(jù)潜支,然后轉(zhuǎn)換成json格式,將NSString格式的數(shù)據(jù)轉(zhuǎn)換成json數(shù)據(jù)柿汛,利用IOS5自帶的json解析方法:
```js
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = operation.responseString;
NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
id dict=[NSJSONSerialization? JSONObjectWithData:data options:0 error:nil];
NSLog(@"獲取到的數(shù)據(jù)為:%@",dict);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"發(fā)生錯(cuò)誤冗酿!%@",error);
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
```
如果發(fā)生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL這個(gè)錯(cuò)誤,請(qǐng)檢查URL編碼格式。有沒有進(jìn)行`stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding`
***
## 如何通過URL獲取圖片
異步獲取圖片裁替,通過隊(duì)列實(shí)現(xiàn)鸠窗,而且圖片會(huì)有緩存,在下次請(qǐng)求相同的鏈接時(shí)胯究,系統(tǒng)會(huì)自動(dòng)調(diào)用緩存稍计,而不從網(wǎng)上請(qǐng)求數(shù)據(jù)。
```js
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i./r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
[self.view addSubview:imageView];
上面的方法是官方提供的裕循,還有一種方法臣嚣,
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.backgroundImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];
[operation start];
```
如果使用第一種URLWithString:? placeholderImage:會(huì)有更多的細(xì)節(jié)處理,其實(shí)實(shí)現(xiàn)還是通過AFImageRequestOperation處理剥哑,可以點(diǎn)擊URLWithString:? placeholderImage:方法進(jìn)去看一下就一目了然了硅则。所以我覺得還是用第一種好。
***
## 如何通過URL獲取plist文件
```js
通過url獲取plist文件的內(nèi)容株婴,用的很少怎虫,這個(gè)方法在官方提供的方法里面沒有
NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";
NSURL *url = [NSURL URLWithString:[weatherUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
NSLog(@"%@",(NSDictionary *)propertyList);
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
NSLog(@"%@",error);
}];
[operation start];
如果稍不留神,可能就出現(xiàn)Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {(
"application/x-plist"
)}, got text/plain" UserInfo=0x16e91ce0 {NSLocalizedRecoverySuggestion=
...
...
, AFNetworkingOperationFailingURLRequestErrorKey= { }, NSErrorFailingURLKey=, NSLocalizedDescription=Expected content type {(
"application/x-plist"
)}, got text/plain, AFNetworkingOperationFailinponseErrorKey= { URL:? } { status code: 200, headers {
"Accept-Ranges" = bytes;
Connection = "keep-alive";
"Content-Length" = 974;
"Content-Type" = "text/plain";
Date = "Sat, 25 Jan 2014 07:29:26 GMT";
Etag = ""1014c2-3ce-4ee63e1c80e00"";
"Last-Modified" = "Wed, 25 Dec 2013 23:04:24 GMT";
Server = "nginx/1.4.2";
} }}
```
可能還會(huì)出現(xiàn)亂碼困介,解決辦法就是[AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];