一、需要引入的文件:
这两种方式,都可以写在自己的网络数据交互类里面,然后也封装一个block方法,将从服务器端成功获取到的数据传递给具体的controller用于显示。
有什么好的使用建议,大家可以共同讨论。
1.AFNetworking源码文件:
2.所需Library:
二、简单的使用流程:
//具体的后台服务地址
static NSString *const BaseURLString = @"www.xx.com/";
/*****************用法一*********************/
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
//用于存放需要传递给服务端的参数
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:1];
[parameters setObject:参数值 forKey:参数名];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:@"Accept" value:@"application/json"];
NSString *path = @"具体的服务端处理接口";//例如restful的"xx/yy/zz"
/*发送请求。可以使用getPath来获取数据,也可以用postPath来更新服务器数据,
这里只列举了post的用法,get与post的写法类似。*/
[client postPath:path
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
//交互成功:responseObject包含了从服务器回传的信息
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//交互失败:error记录了具体的错误信息
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"获取数据失败"
message:error
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
}
];
/*****************用法二(operation的方式)*********************/
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BaseURLString,@"具体的服务端处理接口"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:baseURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0f];
//传递的参数
NSString *postString = @"keywords=嘟囔";
NSStringEncoding enc = NSUTF8StringEncoding;
NSData *postData = [postString dataUsingEncoding: enc allowLossyConversion: YES];
//设置Method
[request setHTTPMethod: @"POST"];
//装载内容
[request setHTTPBody:postData];
AFJSONRequestOperation *operation
= [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
//交互成功:JSON包含了从服务器回传的信息
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
//交互失败:error记录了具体的错误信息
NSLog(@"ERROR: %@", error);
}];
[operation start];
这两种方式,都可以写在自己的网络数据交互类里面,然后也封装一个block方法,将从服务器端成功获取到的数据传递给具体的controller用于显示。
三、UIImageView+AFNetworking
这个东东很好用。可以异步的加载网络图片。
具体的用法也很简单:
#import "UIImageView+AFNetworking.h"
[需要异步加载图片的imageView setImageWithURL:[NSURL URLWithString:图片存放的可访问的网络地址] placeholderImage:[UIImage imageNamed:placeholder图片]];
有什么好的使用建议,大家可以共同讨论。