AFNetworking的學習

如何選擇AFNetworking版本

首先得下載AFNetworking庫文件,下載時得首先弄清楚,你將要開發的軟件兼容的最低版本是多少。AFNetworking 2.0或者之後的版本需要xcode5.0版本並且只能爲IOS6或更高的手機系統上運行,如果開發MAC程序,那麼2.0版本只能在MAC OS X 10.8或者更高的版本上運行。

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

如果你想要兼容IOS5或MAC OS X 10.7,那你需要用最新發布的1.x版本

AFNetworking 1.x的下載地址https://github.com/AFNetworking/AFNetworking/tree/1.x

如果要兼容4.3或者MAC OS X 10.6,需要用最新發布的0.10.x版本

AFNetworking 0.10.xhttps://github.com/AFNetworking/AFNetworking/tree/0.10.x

如何通過URL獲取json數據

第一種,利用AFJSONRequestOperation官方網站上給的例子:

  

[objc] view plaincopy
  1. NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];  
  2.    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  
  3.    NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  4.    //    從URL獲取json數據  
  5.    AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {  
  6.                NSLog(@"獲取到的數據爲:%@",JSON);  
  7.    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {  
  8.        NSLog(@"發生錯誤!%@",error);  
  9.    }];  
  10.    [operation1 start];  

第二種方法,利用AFHTTPRequestOperation 先獲取到字符串形式的數據,然後轉換成json格式,將NSString格式的數據轉換成json數據,利用IOS5自帶的json解析方法:

 

[objc] view plaincopy
  1. NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];  
  2.   NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  
  3.   NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  4.  AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];  
  5.   [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, idresponseObject) {  
  6.       NSString *html = operation.responseString;  
  7.            NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];  
  8.            id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];  
  9.       NSLog(@"獲取到的數據爲:%@",dict);  
  10.   }failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  11.       NSLog(@"發生錯誤!%@",error);  
  12.   }];  
  13.   NSOperationQueue *queue = [[NSOperationQueue alloc] init];  
  14.   [queue addOperation:operation];  

如果發生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL這個錯誤,請檢查URL編碼格式。有沒有進行stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding


如何通過URL獲取圖片

異步獲取圖片,通過隊列實現,而且圖片會有緩存,在下次請求相同的鏈接時,系統會自動調用緩存,而不從網上請求數據。

[objc] view plaincopy
  1. UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f100.0f100.0f100.0f)];      [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];      [self.view addSubview:imageView];  
  2. 上面的方法是官方提供的,還有一種方法,  
  3. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];  
  4.     AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse*response, UIImage *image) {  
  5.         self.backgroundImageView.image = image;  
  6.     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {  
  7.         NSLog(@"Error %@",error);  
  8.     }];  
  9.    
  10.     [operation start];  

如果使用第一種URLWithString  placeholderImage會有更多的細節處理,其實實現還是通過AFImageRequestOperation處理,可以點擊URLWithString  placeholderImage方法進去看一下就一目瞭然了。所以我覺得還是用第一種好。


如何通過URL獲取plist文件

通過url獲取plist文件的內容,用的很少,這個方法在官方提供的方法裏面沒有

  

[objc] view plaincopy
  1. NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";  
  2.   NSURL *url = [NSURL URLWithString:[weatherUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  
  3.   NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  4.   [AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];  
  5.   AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest *request,NSHTTPURLResponse *response, id propertyList) {  
  6.       NSLog(@"%@",(NSDictionary *)propertyList);  
  7.         
  8.   }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, idpropertyList) {  
  9.       NSLog(@"%@",error);  
  10.   }];  
  11.   
  12.   [operation start];  

如何通過URL獲取XML數據

xml解析使用AFXMLRequestOperation需要實現蘋果自帶的NSXMLParserDelegate委託方法,XML中有一些不需要的協議格式內容,所以就不能像json那樣解析,還得實現委託。我之前有想過能否所有的XML鏈接用一個類處理,而且跟服務端做了溝通,結果很不方便,效果不好。XML大多標籤不同,格式也不固定,所以就有問題,使用json就要方便的多。

第一步;在.h文件中加入委託NSXMLParserDelegate

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

    

[objc] view plaincopy
  1. NSURL *url = [NSURL URLWithString:@"http://113.106.90.22:5244/sshopinfo"];  
  2.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  
  3.     AFXMLRequestOperation *operation =  
  4.     [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {  
  5.         XMLParser.delegate = self;  
  6.         [XMLParser setShouldProcessNamespaces:YES];  
  7.         [XMLParser parse];  
  8.     }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser*XMLParser) {  
  9.         NSLog(@"%@",error);  
  10.     }];  
  11.     [operation start];  

第三步;在.m文件中實現委託方法

    //在文檔開始的時候觸發

-

[objc] view plaincopy
  1. (void)parserDidStartDocument:(NSXMLParser *)parser{  
  2.     NSLog(@"解析開始!");  
  3. }  
  4. //解析起始標記  
  5. - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*)attributeDict{  
  6.     NSLog(@"標記:%@",elementName);  
  7.       
  8. }  
  9. //解析文本節點  
  10. - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{  
  11.     NSLog(@"值:%@",string);  
  12. }  
  13. //解析結束標記  
  14. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{  
  15.     NSLog(@"結束標記:%@",elementName);  
  16. }  
  17. //文檔結束時觸發  
  18. -(void) parserDidEndDocument:(NSXMLParser *)parser{  
  19.     NSLog(@"解析結束!");  
  20. }  

運行的結果:

如何使用AFHTTPClient進行web service操作

[objc] view plaincopy
  1. AFHTTPClient處理GET 和 POST請求.做網頁的朋友們這個方法用的比較多。在要經常調用某個請求時,可以封裝,節省資源。  
  2.    BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";  
  3.     NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];  
  4.     NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];  
  5.     AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];  
  6.       
  7.     [client registerHTTPOperationClass:[AFJSONRequestOperation class]];  
  8.     [client setDefaultHeader:@"Accept" value:@"text/html"];  
  9.     [client postPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation*operation, id responseObject) {  
  10.         NSString* newStr = [[NSString alloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];  
  11.         NSLog(@"POST請求:%@",newStr);  
  12.     }failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  13.         NSLog(@"%@",error);  
  14.     }];  
  15.       
  16.     [client getPath:@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation*operation, id responseObject) {  
  17.         NSString* newStr = [[NSString alloc] initWithData:responseObjectencoding:NSUTF8StringEncoding];  
  18.         NSLog(@"GET請求:%@",newStr);  
  19.     }failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  20.         NSLog(@"%@",error);  
  21.     }];  

運行結果:


如果需要顯示網絡活動指示器,可以用下面方法:

[objc] view plaincopy
  1. [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}

返回數據格式不對。註銷這句話: op.responseSerializer = [AFJSONResponseSerializerserializer];然後將返回的數據自己轉換。

</pre><div></div><pre>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章