AFNetworking使用總結

1 將AFNetWorking文件夾導入項目 
 
2 添加類庫 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework 
3 在使用的地方  #import "AFNetworking.h" 
 
 
解決編譯時警告: 
 
Prefix.pch文件中加入 
#import <SystemConfiguration/SystemConfiguration.h> 
#import <MobileCoreServices/MobileCoreServices.h> 
 
 
注:AFNetWorking使用了ARC ,在不使用ARC項目中使用時,對AFNetWorking的所有.m文件添加“-fobjc-arc” 
    在使用ARC項目中,使用“不使用ARC”的類庫時,對類庫的.m文件添加“-fno-objc-arc” 
  
 
 
[plain] view plaincopy 
 
  1. static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";    
        // 1      NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];      NSURL *url = [NSURLURLWithString:weatherUrl];      NSURLRequest *request = [NSURLRequestrequestWithURL:url];       // 2      AFJSONRequestOperation *operation =      [AFJSONRequestOperationJSONRequestOperationWithRequest:request                                                success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) {                                                   //                                                   NSDictionary*dicWeather = (NSDictionary *)JSON;                                                   NSLog(@"result:%@",dicWeather);                                                }                                                failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) {                                                   UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather"                                                                                                 message:[NSStringstringWithFormat:@"%@",error]                                                                                                delegate:self                                                                                        cancelButtonTitle:@"OK"                                                                                        otherButtonTitles: nil];                                                   [alertView show];                                                }];      // 5      [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 
 
[list=1](1)#import “UIImageView+AFNetworking.h”  (2)UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];      __weak UIImageView *_imageView = imageView;      [imageViewsetImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]]                     placeholderImage:[UIImage imageNamed:@"placeholder.png"]                             success:^(NSURLRequest *request,NSHTTPURLResponse *response, UIImage *image) {                                _imageView.image = image;    
                              [_imageView setNeedsDisplay];                             }                             failure:^(NSURLRequest *request, NSHTTPURLResponse*response, NSError *error) {                                ;                             }];      [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 
 
[list=1]AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:baseURL];  [clientregisterHTTPOperationClass:[AFJSONRequestOperation class]];  [clientsetDefaultHeader:@"Accept" value:@"application/json"];  [client postPath:@"weather.php"                parameters:parameters                  success:^(AFHTTPRequestOperation *operation, id responseObject) {                       self.weather =responseObject;                       self.title = @"HTTPPOST";                       [self.tableViewreloadData];                   }                  failure:^(AFHTTPRequestOperation *operation, NSError*error) {                       UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"                                                                   message:[NSStringstringWithFormat:@"%@",error]                                                                  delegate:nil                                                         cancelButtonTitle:@"OK" otherButtonTitles:nil];                       [av show];                    }           ];    
[client getPath:@"weather.php"               parameters:parameters                 success:^(AFHTTPRequestOperation *operation, id responseObject) {                      self.weather =responseObject;                      self.title = @"HTTP GET";                      [self.tableViewreloadData];                  }                 failure:^(AFHTTPRequestOperation *operation, NSError*error) {                      UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"                                                                   message:[NSStringstringWithFormat:@"%@",error]                                                                 delegate:nil                                                        cancelButtonTitle:@"OK" otherButtonTitles:nil];                      [av show];    
                }           ];   
 
另外,請求方式可以創建一個類繼承AFHTTPClient ,官方的例子就是這樣寫的。 
 
狀態欄設置 
  在Appdelegate裏面的 - (BOOL)application:(UIApplication *)application  
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加 [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];用來給用戶做出網絡訪問的提示。 
 
請求超時設置 
timeout和參數都是在NSURLRequest/NSMutableURLRequest設置的  
複製代碼 
[list=1] NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"/" parameters:nil];//這裏的parameters:參數就是你的第二個問題如何設置參數[request setTimeoutInterval:120];AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^{...} failure:^{...}];[client enqueueHTTPRequestOperation:operation]; 
  
  
如果你是繼承了AFHTTPClient  
就需要override一個方法requestWithMethod  
複製代碼
  1. - (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters{    
  2. NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];   
  3. [request setTimeoutInterval:15];    
  4. return request; }
 
  
這個時候的參數設置是調用  
複製代碼
  1. [self postPath:@"" parameters:nil //參數
  2.            success:^(AFHTTPRequestOperation *operation, id responseObject) {
  3.                if (success) {
  4.                    success((AFJSONRequestOperation *)operation, responseObject);
  5.                }
  6.            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  7.                if (failure) {
  8.                    failure((AFJSONRequestOperation *)operation, error);
  9.                }
  10.            }];
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章