AFNetworking框架使用浅析

1、为什么要用 AFNetworking

2、AFNetworking

一、为什么要用 AFNetworking

在iOS开发中,一般情况下,简单的向某个web站点简单的页面提交请求并获取服务器的响应,用Xcode自带的NSURLConnection是能胜任的。但是,在绝大部分下我们所需要访问的web页面则是属于那种受到保护的页面,并不是有一个简单的URL可以访问的。这就涉及到了Session和cookie的处理了,在此时使用NSURLConnection也是能够达到要求的,只是其中处理起来的复杂度和难度就提升了。
为了更好的处理向web站点的请求,包括处理session,cookie等细节问题,使用AFNetworking则是更好的选择,他可以用于发送HTTP请求,接受HTTP的响应,但是不会缓存服务器的响应,不能执行HTML页面中得Javascript代码,同时,AFNetworking还内置支持JSON,Plist文件和XML文件的解析,使用起来比较方便。

扩展:1、session:中文有译作时域的,就是指某个客户端在访问服务器起到停止访问这段时间的间隔称作时域。 2、cookie:由服务器发送给客户端,把cookie的key:value值存在本地文件夹下,当下次请求的时候直接发送cookie获得权限验证。

二、AFNetworking 的用法

1、提交GET请求和提交POST请求

AFNetworking是第三方的框架,所以需要开发者自行下载,安装。并在AFNetworking.h 文件导入 #import”AFHTTPRequestOperationManager.h”,把AFNetworking.h 头文件放入 prefix 文件中。

a、创建 AFHTTPRequestOperationManager 对象

b、根据服务器内容的不同,为 AFHTTPRequestOperationManager 对象指定不同的解析器,该对象默认的解析器是JSON和Plist文件解析器。如果服务器的数据是XML格式则需要手动的更改解析器

c、发送 GET 请求:用Manager 对象调用GET:parameters:success:failure:方法即可,sucess 代码块和 failure 代码块在网络请求成功/失败过后调用。

d、sucess:参数指定了代码块中处理服务器响应成功的正确数据,failure:参数指定了代码块中处理服务器响应失败的错误数据。

AFHTTPRequestOperationManager
包含了常见的HTTP访问web站点的模式,有创建请求,连续响应,网络类型监视以及安全。
GET 请求

// 创建AFHTTPRequestOperationManager 对象  
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManger m anager];   
    // 调用 get 方法
    [manager GET:@"http://example.com/resources.json" parameters: manager
    // 加载成功的代码块,可以接收数据 
 success:^(AFHTTPRequestOperation *operation,id responseobject)]{
    NSLog(@“json“:%@”,responseObject);    
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@“Error:%@”,error);   
  }];

POST 请求

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager mana ger];
    NSDictionary *parameters = @{@"foo": @"bar"};
    [manager POST:@"http://example.com/resources.json" parameters:parameters suc cess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

POST 多个请求

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

2、创建一个下载文件的任务
AFURLSessionManager 创建并完善了一个 NSURLSession 的对象遵守了NSURLSessionDelegate与NSURLSessionDataDelegate协议 NSURLSessionConfigration 对象。

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    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] URLForDir ectory: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];

3、创建一个上传文件的任务

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    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];

4、处理 JSON 或 Plist 响应
iOS应用在处理JSON和Plist响应的时候可以十分轻便将其转换成NSDictionary对象或者NSArray对像,AFHTTPRequestOpeartionManager 默认就可以处理 JSON 或 Plist 响应,也就是说当我们response.MIMEType 为 appication/json、text / json,AFHTTPRequestOpeartionManager 默认就可以处理,无需再次指定服务器响应解析器。

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary  *parameter = @{@"location":@"长沙 ",@"output":@"json",@"ak":@"jlflVx1VTUahj05Q7GfB7PCf"};
    [manager GET:@"http://api.map.baidu.com/telematics/v3/weather?" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"OK");
        dic = responseObject;
        NSArray *keys = [dic allKeys];
        NSLog(@"%@",keys);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"NOT OK");
    }];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值