AFNetworking使用總結(jié)
AFNetworking使用總結(jié)
分享類型:游戲開發(fā)相關(guān)
1 將AFNetWorking文件夾導(dǎo)入項(xiàng)目
2 添加類庫(kù) Security.framework、MobileCoreServices.framework、SystemConfiguration.framework
3 在使用的地方 #import "AFNetworking.h"
解決編譯時(shí)警告:
- Prefix.pch文件中加入
- #import <SystemConfiguration/SystemConfiguration.h>
- #import <MobileCoreServices/MobileCoreServices.h>
注:AFNetWorking使用了ARC ,在不使用ARC項(xiàng)目中使用時(shí),對(duì)AFNetWorking的所有.m文件添加“-fobjc-arc”
在使用ARC項(xiàng)目中,使用“不使用ARC”的類庫(kù)時(shí),對(duì)類庫(kù)的.m文件添加“-fno-objc-arc”
[plain] view plaincopy
- 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)根據(jù)基本的URL構(gòu)造除完整的一個(gè)URL,然后通過(guò)這個(gè)完整的URL獲得一個(gè)NSURL對(duì)象,然后根據(jù)這個(gè)url獲得一個(gè)NSURLRequest。
(2)AFJSONRequestOperation是一個(gè)完整的類,整合了從網(wǎng)絡(luò)中獲取數(shù)據(jù)并對(duì)JSON進(jìn)行解析。
(3)當(dāng)請(qǐng)求成功,則運(yùn)行成功塊。在本例中,把解析出來(lái)的天氣數(shù)據(jù)從JSON變量轉(zhuǎn)換為一個(gè)字典(dictionary),并將其存儲(chǔ)在字典中。
(4)如果運(yùn)行出問(wèn)題了,則運(yùn)行失敗塊(failure block),比如網(wǎng)絡(luò)不可用。如果failure block被調(diào)用了,將會(huì)通過(guò)提示框顯示錯(cuò)誤信息。
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請(qǐng)求
(1).構(gòu)建一個(gè)baseURL,以及一個(gè)參數(shù)字典,并將這兩個(gè)變量傳給AFHTTPClient.
(2).將AFJSONRequestOperation注冊(cè)為HTTP的操作, 這樣就可以跟之前的示例一樣,可以獲得解析好的JSON數(shù)據(jù)。
(3).做了一個(gè)GET請(qǐng)求,這個(gè)請(qǐng)求有一對(duì)block:success和failure。
(4).POST請(qǐng)求跟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];
- } ];
另外,請(qǐng)求方式可以創(chuàng)建一個(gè)類繼承AFHTTPClient ,官方的例子就是這樣寫的。
狀態(tài)欄設(shè)置
在Appdelegate里面的 - (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加 [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];用來(lái)給用戶做出網(wǎng)絡(luò)訪問(wèn)的提示。
請(qǐng)求超時(shí)設(shè)置
timeout和參數(shù)都是在NSURLRequest/NSMutableURLRequest設(shè)置的
- [list=1]
- NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"/" parameters:nil];//這里的parameters:參數(shù)就是你的第二個(gè)問(wèn)題如何設(shè)置參數(shù)
- [request setTimeoutInterval:120];
- AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^{...} failure:^{...}];
- [client enqueueHTTPRequestOperation:operation];
如果你是繼承了AFHTTPClient
就需要override一個(gè)方法requestWithMethod
- - (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters{
- NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
- [request setTimeoutInterval:15];
- return request; }
這個(gè)時(shí)候的參數(shù)設(shè)置是調(diào)用
- [self postPath:@"" parameters:nil //參數(shù)
- success:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success((AFJSONRequestOperation *)operation, responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- if (failure) {
- failure((AFJSONRequestOperation *)operation, error);
- }
- }];
本文鏈接:http://www.cocoachina.com/bbs/read.php?tid=184183