AFNetworking

来源:互联网 发布:上烈士墙的淘宝排行榜 编辑:程序博客网 时间:2024/06/07 02:31

摘要

AFNetworking是一个网络库,适用于iOS以及Mac OS X. 它构建于
NSURLConnection, NSOperation, 以及其他熟悉的Foundation技术之上.

http属于url,url我们叫链接,http我们叫请求和响应
get请求就像明信片,post请求就像信封,东西在请求体中

向服务器请求数据的时候基本上是用的http的请求序列化,是http的表单提交,从服务器返回数据的时候基本上都是json序列化

AFNetWorking:集网络请求和数据解析一起

聚焦:URL、参数、序列化器(请求序列化器默认是http,响应序列化器默认json)

session 要优于 operation,进行了优化

主要包括

NSURLConnection1. AFURLConnectionOperation2. AFHTTPRequestOperation3. AFHTTPRequestOperationManagerNSURLSession (iOS 7 / Mac OS X 10.9)1. AFURLSessionManager2. AFHTTPSessionManager

简单的GET和POST请求,用 AFHTTPRequestOperationManager 就可以,如果有一些上传或下载的任务,就用 AFHTTPSessionManager

对NSURLConnection的封装

AFHTTPRequestOperation

(继承自AFURLConnectionOperation,可用于HTTP请求或HTTPS请求,很少会用到)

//1.创建NSURLRequest对象NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];//2.创建AFHTTPRequestOperation对象(把请求对象传进去)AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];//3.设置 op.responseSerializerop.responseSerializer = [AFJSONResponseSerializer serializer];//4.设置成功之后和失败后的回调方法[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {//请求回来的就已经是对象    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {//失败的情况    NSLog(@"Error: %@", error);}];//5.将AFHTTPRequestOperation对象添加到队列(一般为mainQueue)[[NSOperationQueue mainQueue] addOperation:op];

HTTP Request Operation Manager

manager封装了request的创建、请求序列化器(参数的序列化)、响应序列化器(返回数据的(解析)反序列化)

GET Request

//创建managerAFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];//GET,第二个参数是要传的参数(大多数是字典)[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];

POST URL-Form-Encoded Request(URL的表单编码请求)(用的最多)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];//参数字典(要传的参数)NSDictionary *parameters = @{@"foo": @"bar"};[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];

POST Multi-Part Request(多部分请求,上传数据)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];//参数字典(要传的参数)NSDictionary *parameters = @{@"foo": @"bar"};//获取文件路径的URLNSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];//执行封装好的方法[manager POST:@"http://example.com/resources.json(这是服务器端定好的)" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {//这个代码块用来构造body     //向服务器上传数据    [formData appendPartWithFileURL:filePath name:@"服务器端已经定好的" fileName@"自己定义的文件名" mimeType:@"文件的类型(可以在网上查到)" error:nil];} success:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"Success: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];

Request Serialization(请求序列化器)

通过URL字符串创建一个请求,得到一个GET请求的查询字符串或者POST请求的HTTP body

HTTP请求序列化器

NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];//得到>>> GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];//得到>>> 请求行:POST http://example.com/请求头:Content-Type: application/x-www-form-urlencoded请求体:foo=bar&baz[]=1&baz[]=2&baz[]=3

JSON请求序列化器

NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];//得到>>>请求行:POST http://example.com/请求头:Content-Type: application/json请求体:{"foo": "bar", "baz": [1,2,3]}

对于GET来说,两个序列化器是一样的效果


对NSURLSession的封装

AFURLSessionManager(创建任务,可以跟踪进度,来设置进度条)

Creating a Download Task(下载任务)

//创建配置文件NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];//创建 AFURLSessionManager 管理者AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];//创建 URLRequestNSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];//创建下载任务NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {    //返回最终的文件存储路径(固定写法)    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {    //完成之后    NSLog(@"File downloaded to: %@", filePath);}];[downloadTask resume];

Creating an Upload Task(上传任务)

//创建配置文件NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];//创建 AFURLSessionManager 管理者AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];//创建 NSURLRequestNSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];//获取需要上传的文件路径NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];//创建上传任务NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {    if (error) {        NSLog(@"Error: %@", error);    } else {        NSLog(@"Success: %@ %@", response, responseObject);    }}];[uploadTask resume];

Creating an Upload Task for a Multi-Part Request, with Progress(多部分上传)

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:config];NSString *urlStr = @"http://afnetworking.sinaapp.com/upload2server.json";//上传的参数,是字典类型,多数作为判断是否有上传数据的资格NSDictionary *userInfo = @{@"name":@"poppei"};//创建 NSURLRequest 请求    NSURLRequest *request =[ [AFHTTPRequestSerializer serializer]             multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:userInfo constructingBodyWithBlock:^ (id<AFMultipartFormData> formData){                 NSURL *file1 = [[NSBundle mainBundle]URLForResource:@"a" withExtension:@"jpg"];                 NSURL *file2 = [[NSBundle mainBundle]URLForResource:@"b" withExtension:@"jpg"];                 [formData appendPartWithFileURL:file1 name:@"image" fileName:@"beauty1.jpg" mimeType:@"image/jpeg" error:nil];                 [formData appendPartWithFileURL:file2 name:@"image" fileName:@"beauty2.jpg" mimeType:@"image/jpg" error:nil];    } error:nil];NSProgress *progress;//创建上传任务   NSURLSessionUploadTask *task = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse * response, id responseObject, NSError * error) {        if (error) {            NSLog(@"error>> %@",error);        }        NSLog(@"response >> %@",responseObject);    }];    [task resume];//kvo    [progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:(__bridge void *)(_uploadProgress)];}//观察变化并做出改变-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    //kvc获取监听对象的属性    int64_t comletion = [[object valueForKey:@"completedUnitCount"]longLongValue];    int64_t total = [[object valueForKey:@"totalUnitCount"]longLongValue];    //获取传过来的progressView    UIProgressView *progressView = (__bridge UIProgressView *)(context);    //算比例    float progress = comletion / total;    //更新进度条    dispatch_async(dispatch_get_main_queue(), ^{        progressView.progress = progress;    });}

提示有错误,如果是空心的红点,双击可以进行自动修复

AFHTTPSessionManager

//GET- (IBAction)downLoad:(UIButton *)sender {    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];    NSDictionary *userName = @{@"foo":@"bar"};    [manager GET:@"http://down.tutu001.com/d/file/20101129/2f5ca0f1c9b6d02ea87df74fcc_560.jpg" parameters:userName success:^ void(NSURLSessionDataTask * task, id responseObject) {        NSLog(@"response >> %@",responseObject);    } failure:^ void(NSURLSessionDataTask * task, NSError * error) {        NSLog(@"error >> %@",error);    }];}//POST- (IBAction)upload:(UIButton *)sender {    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];    NSDictionary *userName = @{@"foo":@"bar"};    [manager POST:@"http://afnetworking.sinaapp.com/upload2server.json" parameters:userName success:^ void(NSURLSessionDataTask * task, id responseObject) {        NSLog(@"response >> %@",responseObject);    } failure:^ void(NSURLSessionDataTask * task, NSError * error) {        NSLog(@"error >> %@",error);    }];}//POST多部分- (IBAction)upLoad:(UIButton *)sender {    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];    NSDictionary *userName = @{@"foo":@"bar"};    [manager POST:@"http://afnetworking.sinaapp.com/upload2server.json" parameters:userName constructingBodyWithBlock:^ void(id<AFMultipartFormData> formdata) {        NSURL *file = [[NSBundle mainBundle] URLForResource:@"a" withExtension:@"jpg"];        [formdata appendPartWithFileURL:file name:@"image" fileName:@"myImage" mimeType:@"image/jpeg" error:nil];    } success:^ void(NSURLSessionDataTask * task, id responseObject) {        NSLog(@"response >> %@",responseObject);    } failure:^ void(NSURLSessionDataTask * task, NSError * error) {        NSLog(@"error >> %@",error);    }];}

AFNetWorkReachabilityManager(网络可达性)

监听网络的状态,是wifi还是蜂窝网络

网络的几种状态

NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {    switch (status) {        case AFNetworkReachabilityStatusNotReachable://断网            return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);        case AFNetworkReachabilityStatusReachableViaWWAN://蜂窝网络(流量)            return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);        case AFNetworkReachabilityStatusReachableViaWiFi://无限            return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);        case AFNetworkReachabilityStatusUnknown://不知道        default:            return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);    }}

代码举例

//监听对象 要全局使用@property (nonatomic,strong) AFNetworkReachabilityManager *manger;- (void)viewDidLoad {    [super viewDidLoad];    //单例    _manger = [AFNetworkReachabilityManager sharedManager];    [_manger setReachabilityStatusChangeBlock:^ void(AFNetworkReachabilityStatus status) {        //把状态转换成字符串        NSString *statusStr = AFStringFromNetworkReachabilityStatus(status);        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:statusStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];        [alert show];    }];}//监听网络状态- (IBAction)listen:(UIButton *)sender {    //开启监听    [_manger startMonitoring];}
0 0
原创粉丝点击