AFNetworking的使用

轉自:http://blog.csdn.net/kuro2007/article/details/8945323

1.下載AFNetworking資源包 https://github.com/AFNetworking/AFNetworking

2.將資源包添加到工程文件。

3.在工程的Supporting File羣組中打開預編譯頭文件XXX-Prefix.pch。然後在別的import後面添加如下一行代碼#import “AFNetworking”

將AFNetworking添加到預編譯頭文件,意味着這個框架會被自動的添加到工程的所有源代碼文件中。

4.AFNetworking通過網絡來加載和處理結構化的數據非常明智,它支持JSON,XML,Property List。

[plain] view plaincopy
  1. static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";  
  2.      
  3.     // 1  
  4.     NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];  
  5.     NSURL *url = [NSURLURLWithString:weatherUrl];  
  6.     NSURLRequest *request = [NSURLRequestrequestWithURL:url];  
  7.      
  8.     // 2  
  9.     AFJSONRequestOperation *operation =  
  10.     [AFJSONRequestOperationJSONRequestOperationWithRequest:request  
  11.                                               success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) {  
  12.                                                  //  
  13.                                                  NSDictionary*dicWeather = (NSDictionary *)JSON;  
  14.                                                  NSLog(@"result:%@",dicWeather);  
  15.                                               }  
  16.                                               failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) {  
  17.                                                  UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather"  
  18.                                                                                                message:[NSStringstringWithFormat:@"%@",error]  
  19.                                                                                               delegate:self  
  20.                                                                                       cancelButtonTitle:@"OK"  
  21.                                                                                       otherButtonTitles: nil];  
  22.                                                  [alertView show];  
  23.                                               }];  
  24.     // 5  
  25.     [operation start];  

(1)根據基本的URL構造除完整的一個URL,然後通過這個完整的URL獲得一個NSURL對象,然後根據這個url獲得一個NSURLRequest。

(2)AFJSONRequestOperation是一個完整的類,整合了從網絡中獲取數據並對JSON進行解析。

(3)當請求成功,則運行成功塊。在本例中,把解析出來的天氣數據從JSON變量轉換爲一個字典(dictionary),並將其存儲在字典中。

(4)如果運行出問題了,則運行失敗塊(failure block),比如網絡不可用。如果failure block被調用了,將會通過提示框顯示錯誤信息。

 

6.AFNetWorking異步加載圖片

[plain] view plaincopy
  1. (1)#import “UIImageView+AFNetworking.h”  
  2. (2)UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];  
  3.     __weak UIImageView *_imageView = imageView;  
  4.     [imageViewsetImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]]  
  5.                    placeholderImage:[UIImage imageNamed:@"placeholder.png"]  
  6.                            success:^(NSURLRequest *request,NSHTTPURLResponse *response, UIImage *image) {  
  7.                               _imageView.image = image;  
  8.                                
  9.                               [_imageView setNeedsDisplay];  
  10.                            }  
  11.                            failure:^(NSURLRequest *request, NSHTTPURLResponse*response, NSError *error) {  
  12.                               ;  
  13.                            }];  
  14.     [self.view addSubview:imageView];  
 

7.GET 和POST請求

(1).構建一個baseURL,以及一個參數字典,並將這兩個變量傳給AFHTTPClient.

(2).將AFJSONRequestOperation註冊爲HTTP的操作, 這樣就可以跟之前的示例一樣,可以獲得解析好的JSON數據。

(3).做了一個GET請求,這個請求有一對block:success和failure。

(4).POST請求跟GET一樣

[plain] view plaincopy
  1. AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:baseURL];  
  2. [clientregisterHTTPOperationClass:[AFJSONRequestOperation class]];  
  3. [clientsetDefaultHeader:@"Accept" value:@"application/json"];  
  4. [client postPath:@"weather.php"  
  5.               parameters:parameters  
  6.                 success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  7.                      self.weather =responseObject;  
  8.                      self.title = @"HTTPPOST";  
  9.                      [self.tableViewreloadData];  
  10.                  }  
  11.                 failure:^(AFHTTPRequestOperation *operation, NSError*error) {  
  12.                      UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"  
  13.                                                                  message:[NSStringstringWithFormat:@"%@",error]  
  14.                                                                 delegate:nil  
  15.                                                        cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  16.                      [av show];  
  17.    
  18.                  }  
  19.          ];  
  20.    
  21. [client getPath:@"weather.php"  
  22.              parameters:parameters  
  23.                success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  24.                     self.weather =responseObject;  
  25.                     self.title = @"HTTP GET";  
  26.                     [self.tableViewreloadData];  
  27.                 }  
  28.                failure:^(AFHTTPRequestOperation *operation, NSError*error) {  
  29.                     UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"  
  30.                                                                  message:[NSStringstringWithFormat:@"%@",error]  
  31.                                                                delegate:nil  
  32.                                                       cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  33.                     [av show];  
  34.    
  35.                 }  
  36.          ];  
  

8.AFNetworking更新背景圖片

Note:

AFJSONOperation,AFPropertyListOperation, AFXMLOperation用來解析結構化數據。

UIImageView+AFNetworking用來快捷的填充image view

AFHTTPClient用來進行更底層的請求

用自定義的AFHTTPClient子類來訪問一個web service。

AFNetworkActivityIndicatiorManager用來給用戶做出網絡訪問的提示。

AFImageRequestOperation用來加載圖片。


[plain] view plaincopy
  1.   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章