AFNetworking 理解與使用<三>

一、如何選擇AFNetworking版本

此文章基于AFNetworking2.0

首先得下載AFNetworking庫(kù)文件,下載時(shí)得首先弄清楚,你將要開(kāi)發(fā)的軟件兼容的最低版本是多少。AFNetworking 2.0或者之后的版本需要xcode5.0版本并且只能為IOS6或更高的手機(jī)系統(tǒng)上運(yùn)行。如果開(kāi)發(fā)MAC程序,那么2.0版本只能在MAC OS X 10.8或者更高的版本上運(yùn)行

AFNetworking 2.0的下載地址https://github.com/AFNetworking/AFNetworking

二、獲取網(wǎng)絡(luò)請(qǐng)求

1、如何通過(guò)URL獲取json數(shù)據(jù)

1>、利用AFJSONRequestOperation,官方網(wǎng)站上給的例子:

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];

? ? //? ? 從URL獲取json數(shù)據(jù)

? ? AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {

? ? ? ? ? ? ? ? NSLog(@"獲取到的數(shù)據(jù)為:%@",JSON);

? ? } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {

? ? ? ? NSLog(@"發(fā)生錯(cuò)誤!%@",error);

? ? }];

? ? [operation1 start];

2>、利用AFHTTPRequestOperation?先獲取到字符串形式的數(shù)據(jù),然后轉(zhuǎn)換成json格式,將NSString格式的數(shù)據(jù)轉(zhuǎn)換成json數(shù)據(jù),利用IOS5自帶的json解析方法:

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, idresponseObject) {

? ? ? ? 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編碼格式。有沒(méi)有進(jìn)行stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

2、如何通過(guò)URL獲取圖片

異步獲取圖片,通過(guò)隊(duì)列實(shí)現(xiàn),而且圖片會(huì)有緩存,在下次請(qǐng)求相同的鏈接時(shí),系統(tǒng)會(huì)自動(dòng)調(diào)用緩存,而不從網(wǎng)上請(qǐng)求數(shù)據(jù)。

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)];

[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/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)還是通過(guò)AFImageRequestOperation處理,可以點(diǎn)擊URLWithString:??placeholderImage:方法進(jìn)去看一下就一目了然了。所以我覺(jué)得還是用第一種好。

3、如何通過(guò)URL獲取plist文件

通過(guò)url獲取plist文件的內(nèi)容,用的很少,這個(gè)方法在官方提供的方法里面沒(méi)有。

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, idpropertyList) {

? ? ? ? NSLog(@"%@",error);

? ? }];

? ? [operation start];

4、如何通過(guò)URL獲取XML數(shù)據(jù)

xml解析使用AFXMLRequestOperation,需要實(shí)現(xiàn)蘋(píng)果自帶的NSXMLParserDelegate委托方法,XML中有一些不需要的協(xié)議格式內(nèi)容,所以就不能像json那樣解析,還得實(shí)現(xiàn)委托。我之前有想過(guò)能否所有的XML鏈接用一個(gè)類(lèi)處理,而且跟服務(wù)端做了溝通,結(jié)果很不方便,效果不好。XML大多標(biāo)簽不同,格式也不固定,所以就有問(wèn)題,使用json就要方便的多。

第一步:在.h文件中加入委托NSXMLParserDelegate

第二步:在.m文件方法中加入代碼

NSURL *url = [NSURL URLWithString:@"http://113.106.90.22:5244/sshopinfo"];

? ? NSURLRequest *request = [NSURLRequest requestWithURL:url];

? ? AFXMLRequestOperation *operation =

? ? [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {

? ? ? ? XMLParser.delegate = self;

? ? ? ? [XMLParser setShouldProcessNamespaces:YES];

? ? ? ? [XMLParser parse];

? ? }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser*XMLParser) {

? ? ? ? NSLog(@"%@",error);

? ? }];

? ? [operation start];

第三步:在.m文件中實(shí)現(xiàn)委托方法

?//在文檔開(kāi)始的時(shí)候觸發(fā)

(void)parserDidStartDocument:(NSXMLParser *)parser{

? ? NSLog(@"解析開(kāi)始!");

}

//解析起始標(biāo)記

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*)attributeDict{

? ? NSLog(@"標(biāo)記:%@",elementName);


}

//解析文本節(jié)點(diǎn)

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

? ? NSLog(@"值:%@",string);

}

//解析結(jié)束標(biāo)記

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

? ? NSLog(@"結(jié)束標(biāo)記:%@",elementName);

}

//文檔結(jié)束時(shí)觸發(fā)

-(void) parserDidEndDocument:(NSXMLParser *)parser{

? ? NSLog(@"解析結(jié)束!");

}

5、如何使用AFHTTPClient進(jìn)行web service操作

AFHTTPClient處理GET 和 POST請(qǐng)求.做網(wǎng)頁(yè)的朋友們這個(gè)方法用的比較多。在要經(jīng)常調(diào)用某個(gè)請(qǐng)求時(shí),可以封裝,節(jié)省資源。

? BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";

? ? NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];

? ? NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];

? ? AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];


? ? [client registerHTTPOperationClass:[AFJSONRequestOperation class]];

? ? [client setDefaultHeader:@"Accept" value:@"text/html"];

? ? [client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation*operation, id responseObject) {

? ? ? ? NSString* newStr = [[NSString alloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];

? ? ? ? NSLog(@"POST請(qǐng)求:%@",newStr);

? ? }failure:^(AFHTTPRequestOperation *operation, NSError *error) {

? ? ? ? NSLog(@"%@",error);

? ? }];


? ? [client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation*operation, id responseObject) {

? ? ? ? NSString* newStr = [[NSString alloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];

? ? ? ? NSLog(@"GET請(qǐng)求:%@",newStr);

? ? }failure:^(AFHTTPRequestOperation *operation, NSError *error) {

? ? ? ? NSLog(@"%@",error);

? ? }];

運(yùn)行結(jié)果:

如果需要顯示網(wǎng)絡(luò)活動(dòng)指示器,可以用下面方法:

[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x16774de0 {NSErrorFailingURLKey=http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1, AFNetworkingOperationFailinponseErrorKey= { URL: http://192.168.2.2:8181/ecar/tsp/uploadLocation?CID=781666&serviceType=1 } { status code: 200, headers {

????XXX


} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}

返回?cái)?shù)據(jù)格式不對(duì)。注銷(xiāo)這句話:?op.responseSerializer = [AFJSONResponseSerializerserializer];然后將返回的數(shù)據(jù)自己轉(zhuǎn)換。

demo下載地址:點(diǎn)擊打開(kāi)下載界面

此文章基于AFNetworking2.0,如果您使用的是2.5版本的,請(qǐng)看這篇文章:AFNetworking2.5使用

點(diǎn)擊了解YTKNetwork

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容