AFNetworking使用总结

转自:http://www.cocoachina.com/bbs/read.php?tid=184183

http://blog.****.net/zhangkongzhongyun/article/details/8081094


*****************************************************************************************************************************************************************

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”

AFNetworking使用总结


[plain]view plaincopy

  1. staticNSString*[email protected]"http://www.raywenderlich.com/downloads/weather_sample/";
    //1NSString*weatherUrl=[NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];NSURL*url=[NSURLURLWithString:weatherUrl];NSURLRequest*request=[NSURLRequestrequestWithURL:url]; //2AFJSONRequestOperation*operation=[AFJSONRequestOperationJSONRequestOperationWithRequest:requestsuccess:^(NSURLRequest*request,NSHTTPURLResponse*response,idJSON){//NSDictionary*dicWeather=(NSDictionary*)JSON;NSLog(@"result:%@",dicWeather);}failure:^(NSURLRequest*request,NSHTTPURLResponse*response,NSError*error,idJSON){UIAlertView*alertView=[[UIAlertViewalloc]initWithTitle:@"ErrorRetrievingWeather"message:[NSStringstringWithFormat:@"%@",error]delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];[alertViewshow];}];//5[operationstart];
    (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=[[UIImageViewalloc]initWithFrame:CGRectMake(40,80,40,40)];__weakUIImageView*_imageView=imageView;[imageViewsetImageWithURLRequest:[[NSURLRequestalloc]initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]]placeholderImage:[UIImageimageNamed:@"placeholder.png"]success:^(NSURLRequest*request,NSHTTPURLResponse*response,UIImage*image){_imageView.image=image;
[_imageViewsetNeedsDisplay];}failure:^(NSURLRequest*request,NSHTTPURLResponse*response,NSError*error){;}];[self.viewaddSubview: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=[[AFHTTPClientalloc]initWithBaseURL:baseURL];[clientregisterHTTPOperationClass:[AFJSONRequestOperationclass]];[clientsetDefaultHeader:@"Accept"value:@"application/json"];[clientpostPath:@"weather.php"parameters:parameterssuccess:^(AFHTTPRequestOperation*operation,idresponseObject){self.weather=responseObject;[email protected]"HTTPPOST";[self.tableViewreloadData];}failure:^(AFHTTPRequestOperation*operation,NSError*error){UIAlertView*av=[[UIAlertViewalloc]initWithTitle:@"ErrorRetrievingWeather"message:[NSStringstringWithFormat:@"%@",error]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil];[avshow]; }];
[clientgetPath:@"weather.php"parameters:parameterssuccess:^(AFHTTPRequestOperation*operation,idresponseObject){self.weather=responseObject;[email protected]"HTTPGET";[self.tableViewreloadData];}failure:^(AFHTTPRequestOperation*operation,NSError*error){UIAlertView*av=[[UIAlertViewalloc]initWithTitle:@"ErrorRetrievingWeather"message:[NSStringstringWithFormat:@"%@",error]delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil];[avshow];
}];

另外,请求方式可以创建一个类继承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. }];

****************************************************************************************************************

AFNetworking 如何POST一个JSON数据到服务器

NSString *[email protected]"http://www.baidu.com" ;

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@""]];//这里要将url设置为空

httpClient.parameterEncoding = AFJSONParameterEncoding;

[httpClient setDefaultHeader:@"Accept" value:@"text/json"];

NSMutableDictionary *params=[[NSMutableDictionary alloc] init]; // 要传递的json数据是一个字典

[params setObject:UserID forKey:@"userId"];

[params setObject:[self.contDic objectForKey:@"weiboId" ] forKey:@"operateId"];

[params setObject:@"8d0ce196d0eafa27780cc3a7217de71d92474021dc0a4fc593d4f9b9eda320ca" forKey:@"key"];

// httpClient 的postPath就是上文中的pathStr,即你要访问的URL地址,这里是向服务器提交一个数据请求,

[httpClient postPath:pathStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"data====%@",params);

NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

NSLog(@"Request Successful, response '%@'", responseStr);

[responseStr release];

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

NSLog(@"[HTTPClient Error]: %@", error);