标签:ios开发 github 网络 afnetworki
什么是AFN
全称是AFNetworking,是对NSURLConnection、NSURLSession的一层封装
虽然运行效率没有ASI高,但是使用比ASI简单
在iOS开发中,使用比较广泛
AFN的github地址
https://github.com/AFNetworking/AFNetworking
是AFN中最重要的对象之一
封装了HTTP请求的常见处理
GET\POST请求
解析服务器的响应数据
创建
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//GET请求
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
//POST请求
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager startMonitoring];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"%d", status);
}];
提示:要监控网络连接状态,必须要先调用单例的startMonitoring方法
1.AFHTTPRequestOperationManager
* 对NSURLConnection的封装
2.AFHTTPSessionManager
* 对NSURLSession的封装
1.AFN可以自动对服务器返回的数据进行解析
* 默认将服务器返回的数据当做JSON来解析
2.设置对服务器返回数据的解析方式
1> 当做是JSON来解析(默认做法)
* mgr.responseSerializer = [AFJSONResponseSerializer serializer];
* responseObject的类型是NSDictionary或者NSArray
2> 当做是XML来解析
* mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
* responseObject的类型是NSXMLParser
3> 直接返回data
* 意思是:告诉AFN不要去解析服务器返回的数据,保持原来的data即可
* mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
3.注意
* 服务器返回的数据一定要跟responseSerializer对得上
1> 服务器返回的是JSON数据
* AFJSONResponseSerializer
* AFHTTPResponseSerializer
2> 服务器返回的是XML数据
* AFXMLParserResponseSerializer
* AFHTTPResponseSerializer
3> 服务器返回的是其他数据
* AFHTTPResponseSerializer
#import "AFNetworking.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self postJSON];
}
- (void)getSession
{
// AFHTTPSessionManager 对 NSURLSession 的封装
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
[mgr GET:@"" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
}
/**
* 利用AFN发送一个POST请求,服务器返回的JSON数据
*/
- (void)postJSON
{
// AFHTTPRequestOperationManager 对 NSURLConnection的封装
// 1.创建一个请求操作管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 2.请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"哈哈哈";
params[@"pwd"] = @"123";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr POST:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功的时候调用这个block
NSLog(@"请求成功---%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败的时候调用调用这个block
NSLog(@"请求失败");
}];
}
/**
* 利用AFN发送一个GET请求,服务器返回的JSON数据,让AFN直接返回data
*/
- (void)getData
{
// 1.创建一个请求操作管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 声明:不要对服务器返回的数据进行解析,直接返回data即可
// 如果是文件下载,肯定是用这个
// responseObject的类型是NSData
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
// 2.请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"哈哈哈";
params[@"pwd"] = @"123";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr GET:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功的时候调用这个block
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@", dict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败的时候调用调用这个block
NSLog(@"请求失败");
}];
}
/**
* 利用AFN发送一个GET请求,服务器返回的XML数据
*/
- (void)getXML
{
// 1.创建一个请求操作管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 声明:等会服务器返回的是XML数据
// responseObject的类型是NSXMLParser
mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
// 2.请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"哈哈哈";
params[@"pwd"] = @"123";
params[@"type"] = @"XML";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/MJServer/login";
[mgr GET:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功的时候调用这个block
NSLog(@"请求成功--%@", responseObject);
// responseObject.delegate = self;
// [responseObject parse];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败的时候调用调用这个block
NSLog(@"请求失败");
}];
}
/**
* 利用AFN发送一个GET请求,服务器返回的JSON数据
*/
- (void)getJSON
{
// 1.创建一个请求操作管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 声明一下:服务器返回的是JSON数据
// mgr.responseSerializer = [AFJSONResponseSerializer serializer];
// responseObject的类型是NSDictionary或者NSArray
// 2.请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"哈哈哈";
params[@"pwd"] = @"123";
// 3.发送一个GET请求
NSString *url = @"http://localhost:8080/Server/login";
[mgr GET:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功的时候调用这个block
NSLog(@"请求成功---%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败的时候调用调用这个block
NSLog(@"请求失败");
}];
}
@end
#import "AFNetworking.h"
@interface ViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)upload;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"相册", nil];
[sheet showInView:self.view.window];
}
#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
// 设置代理
ipc.delegate = self;
switch (buttonIndex) {
case 0: { // 拍照
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
break;
}
case 1: { // 相册
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
break;
}
default:
break;
}
// 显示控制器
[self presentViewController:ipc animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
/**
* 在选择完图片后调用
*
* @param info 里面包含了图片信息
*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 销毁控制器
[picker dismissViewControllerAnimated:YES completion:nil];
// 获得图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
// 显示图片
self.imageView.image = image;
}
- (void)upload1
{
// 1.创建一个管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 2.封装参数(这个字典只能放非文件参数)
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"123";
params[@"age"] = @20;
params[@"pwd"] = @"456";
params[@"height"] = @1.55;
// 2.发送一个请求
NSString *url = @"http://localhost:8080/MJServer/upload";
[mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 在发送请求之前会自动调用这个block
// 需要在这个block中添加文件参数到formData中
/**
FileURL : 需要上传的文件的URL路径
name : 服务器那边接收文件用的参数名
fileName : (告诉服务器)所上传文件的文件名
mimeType : 所上传文件的文件类型
*/
NSURL *url = [[NSBundle mainBundle] URLForResource:@"itcast" withExtension:@"txt"];
[formData appendPartWithFileURL:url name:@"file" fileName:@"test.txt" mimeType:@"text/plain" error:nil];
/**
FileData : 需要上传的文件的具体数据
name : 服务器那边接收文件用的参数名
fileName : (告诉服务器)所上传文件的文件名
mimeType : 所上传文件的文件类型
*/
// UIImage *image = [UIImage imageNamed:@"minion_01"];
// NSData *fileData = UIImagePNGRepresentation(image);
// [formData appendPartWithFileData:fileData name:@"file" fileName:@"haha.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传失败");
}];
}
- (IBAction)upload {
if (self.imageView.image == nil) return;
// 1.创建一个管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 2.封装参数(这个字典只能放非文件参数)
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"username"] = @"123";
params[@"age"] = @20;
params[@"pwd"] = @"456";
params[@"height"] = @1.55;
// 2.发送一个请求
NSString *url = @"http://192.168.15.172:8080/Server/upload";
[mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
[formData appendPartWithFileData:fileData name:@"file" fileName:@"haha.jpg" mimeType:@"image/jpeg"];
// 不是用这个方法来设置文件参数
// [formData appendPartWithFormData:fileData name:@"file"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传失败");
}];
// 文件下载,文件比较大,断点续传技术:普遍所有的HTTP服务器都支持
// 文件上传,文件比较大,断点续传技术:一般的HTTP服务器都不支持,常用的技术用的是Socket(TCP\IP、UDP)
}
@end
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:ios开发 github 网络 afnetworki
原文地址:http://blog.csdn.net/wangzi11322/article/details/49612579