Fork me on GitHub

第三方之---------------AFNetworking 2.5.0版本的使用

    众所周知,苹果搞的一套框架NSContention发送请求与接收请求的方式十分繁琐。操作起来很不方便。不仅要做区分各种请求设置各种不同的参数,而且还要经常在多线程里操作,同时还要对请求与返回的数据做各种序列化的操作,同时还要考虑请求数据的安全等一堆问题。


一、早前的几个网络框架
1、ASI框架: HTTP终结者.很牛, 但是有BUG, 已经停止更新.
2、MKNetworkKit (印度人写的).
3、AFN一直还在更新.

AFNetworking的出现:MAC/iOS设计的一套网络框架.(为了简化网络操作)

*AFN专注与网络数据传输,以及网络中多线程的处理.

 

二、AFNetworking的使用

1、AFN特性 :
*登录传参数时,传递字典即可.(键名为参数名,键值为参数值).
*自动到子线程中执行,执行完后返回主线程.
*返回的结果自动序列化为NSDictionary.

2、使用AFN注意 :
*AFHTTPRequestOperationManager封装了通过HTTP协议与Web应用程序进行通讯的常用方法.(这个实例化的时候不是单例, 因为没有shared字)
*包括创建请求/响应序列化/网络监控/数据安全.
*方法等都是以AF开头的.

 

3、AFN能做的 (网络中的都涵盖了):
*GET/POST/PUT/DELETE/HEAD请求.
*JSON数据解析/Plist数据解析.(不支持XML数据解析)
*POSTJSON.
*上传/下载.

 

4、使用步骤 : (可参考说明文档)
1.首先需要实例化一个请求管理器AFHTTPRequestOperationManager.
2.设置请求的数据格式:默认是二进制.(不是可改)
*AFHTTPRequestSerializer(二进制)
*AFJSONRequestSerializer(JSON)
*AFPropertyListRequestSerializer(Plist)
3.设置响应的数据格式:默认是JSON.(不是可改)
*AFHTTPResponseSerializer(二进制)
*AFJSONResponseSerializer(JSON)
*AFPropertyListResponseSerializer(Plist)
*AFXMLParserResponseSerializer(XML)
*AFImageResponseSerializer(Image)
*AFCompoundResponseSerializer(组合的)
4.如果响应者的MIMEType不正确,就要修改acceptableContentTypes.
5.调用方法,发送响应的请求(GET/POST...).



 

 

 

三.AFNetworking 2.5.0版本的使用演示说明

http://afnetworking.com/

http://cocoadocs.org/docsets/AFNetworking/2.5.0/

 

1. 下载源码并进行编译

源码地址 http://pan.baidu.com/s/1jG24w3W

 

2. 判断当前是否有网络,基准网址为 http://baidu.com/

 

源码:

可以用来监测WWAN或者WiFi或者断网状态;)

    // 基准baseURL
    NSURL *baseURL                         = [NSURL URLWithString:@"http://baidu.com/"];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    NSOperationQueue *operationQueue       = manager.operationQueue;
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                
                // 此处可以发送有网络通知
                NSLog(@"有网络");
                
                break;
            case AFNetworkReachabilityStatusNotReachable:
            default:
                [operationQueue setSuspended:YES];
                
                // 此处可以发送断网通知
                NSLog(@"断网了");
                
                break;
        }
    }];
    
    // 开始监测网络
    [manager.reachabilityManager startMonitoring];

 

3. 不带参数的GET请求

源码:

    // 初始化网址
    NSString *requestAddress = \
        @"http://api.openweathermap.org/data/2.5/forecast/daily?lat=39.88293652833437&lon=116.4621119300779&lang=zh_cn";
    
//1.请求管理器 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; //2.请求 -- 不带参数的GET请求 [manager GET:requestAddress parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];

 

4. 带参数GET的请求

源码:

    // 初始化网址
    NSString *requestAddress = \
        @"http://api.openweathermap.org/data/2.5/forecast/daily";
    //1.请求管理器
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
//2.设置登录参数
NSDictionary *dict = @{@"lat" : @"39.88293652833437", @"lon" : @"116.4621119300779", @"lang" : @"zh_cn"};
//3.请求 -------参数的GET请求 [manager GET:requestAddress parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];

 

5. 不带参数的POST请求

源码:

    // 初始化网址
    NSString *cityName       = [@"北京" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *requestAddress = \
        [NSString stringWithFormat:@"http://apis.haoservice.com/weather?cityname=%@&key=1d309cc633984df791b51f48ddf09d4b", cityName];
    
//1.请求管理器 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer.acceptableContentTypes = \ [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; // 2.请求 -------不带参数的POST请求 [manager POST:requestAddress parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];

 

6. 带参数的POST请求

源码:

    // 初始化网址
    NSString *cityName   = [@"北京" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *requestAddress = \
        [NSString stringWithFormat:@"http://apis.haoservice.com/weather"];
    //1.请求管理者
    AFHTTPRequestOperationManager *manager  = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = \
        [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

//2.请求登录参数
NSDictionary *dict = @{@"cityname" : cityName, @"key" : @"1d309cc633984df791b51f48ddf09d4b"}; //3.请求 -----------------带参数的POST请求 [manager POST:requestAddress parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];

 

附录:

基于URL-form-encodes Body方式的POST请求

    // 初始化网址
    NSString *cityName  = [@"北京" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *requestAddress = 
        [NSString stringWithFormat:@"http://apis.haoservice.com/weather"];
    //1.请求管理器
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//2. 设定类型 // 创建 URL-form-encodes HTTP message bodies manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 接受的数据类型 manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; //3.发送请求 带参数的POST请求 [manager POST:requestAddress parameters:@{@"cityname" : cityName, @"key" : @"1d309cc633984df791b51f48ddf09d4b"} success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];

 

7. 文件下载  用AFN来POST JSON数据,上传、下载等

//
//  ViewController.m
//  AFNetworking2.5.0
//
//  Created by XianMingYou on 15/2/14.
//  Copyright (c) 2015年 XianMingYou. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 定义一个progress指针
    NSProgress *progress;
    
    // 创建一个URL链接
    NSURL *url = [NSURL URLWithString:@"http://41.duote.com.cn/2345explorer.exe"];
    
    // 初始化一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 获取一个Session管理器
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    // 开始下载任务
    NSURLSessionDownloadTask *downloadTask = \
        [session downloadTaskWithRequest:request
                                progress:&progress
                             destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
         {
             // 拼接一个文件夹路径
             NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                                                   inDomain:NSUserDomainMask
                                                                          appropriateForURL:nil
                                                                                     create:NO
                                                                                      error:nil];
             
             // 根据网址信息拼接成一个完整的文件存储路径并返回给block
             return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
             
         } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
         {
             // 结束后移除掉这个progress
             [progress removeObserver:self
                           forKeyPath:@"fractionCompleted"
                              context:nil];
         }];
    
    // 设置这个progress的唯一标示符
    [progress setUserInfoObject:@"someThing" forKey:@"Y.X."];
    [downloadTask resume];
    
    // 给这个progress添加监听任务
    [progress addObserver:self
               forKeyPath:@"fractionCompleted"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        NSLog(@"Progress is %f", progress.fractionCompleted);
    }
}

@end

 

8. 文件上传

单文件上传 - (没有办法做试验演示)

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];

多文件上传 - (没有办法做试验演示)

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];

[uploadTask resume];

 

9. Request Serialization

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

请求序列化是为了从URL字符串创建出编码后的参数,或者是序列字典,或者是HTTP实体.

NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

QUERY STRING PARAMETER ENCODING

字符串序列编码

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET请求 http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL FORM PARAMETER ENCODING

URL表单编码

[[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 PARAMETER ENCODING

JSON编码

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST请求 http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}
 
 
 
 推荐文章:http://blog.csdn.net/xn4545945/article/details/37945711 里面有详细解释和使用步骤
 
 
 
 
 
 
posted @ 2015-10-31 17:43  DengHuiCheng  阅读(209)  评论(0编辑  收藏  举报