AFNetworking

原创 2015年11月19日 11:55:09

摘要

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

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

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

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

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

session 要优于 operation,进行了优化

主要包括

NSURLConnection

1. AFURLConnectionOperation
2. AFHTTPRequestOperation
3. AFHTTPRequestOperationManager

NSURLSession (iOS 7 / Mac OS X 10.9)

1. AFURLSessionManager
2. 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.responseSerializer
op.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

//创建manager
AFHTTPRequestOperationManager *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"};
//获取文件路径的URL
NSURL *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];
//创建 URLRequest
NSURL *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];
//创建 NSURLRequest
NSURL *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];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

关于UITextView的封装

目前能够实现的功能: 设置占位字符,可以设置占位字符的字体大小,字体颜色,字体高亮颜色,也可以设置属性字符串作为占位字符 设置最大行数,超过最大行数之后滚动显示 设置最多输入的文字个数,超过之后不能输...

runtime从入门到精通(八)—— 使用runtime实现字典转模型

由于文章篇幅长度原因,笔者单独用一篇文章来介绍使用runtime来实现字典转模型。查看完整的runtime在实际开发中的使用点击链接 ——> runtime从入门到精通(六)—— runtime在实际...

IOS四种反向传值的方法

方法一:使用target-action设计模式代码如下:(由根视图推出子视图,再由子视图推出根视图,在推出根视图时,子视图传一个color的属性给根视图,用来修改根视图的背景颜色)根视图控制器代码:/...

防止按钮快速连续点击造成多次响应的方法

用户快速点击某个按钮,导致页面重复push或者重复发送网络请求。这样的问题既对用户体验有影响,而且还会一定程度上增加服务器的压力。主要使用以下办法:在每次点击时先取消之前的操作- (void)butt...

iOS-常见加密总结

**随着信息化的到来,互联网的快速发展,数据安全越来越受到重视。只要关于个人隐私和金钱等有关的信息,都需要进行加密。 如今,移动端包含了众多的个人隐私,只要信息安全的App才会被用户所信任使用。**...

在nsobject的分类中增加方法来避免使用kvc赋值的时候出现崩溃

在有些时候我们需要通过KVC去修改某个类的私有变量,但是又不知道该属性是否存在,如果类中不存在该属性,那么通过KVC赋值就会crash,这时也可以通过运行时进行判断。同样我们在NSObject的分类中...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)