关于AFNetworking 类库的一般用法

来源:互联网 发布:sql统计小计合计查询 编辑:程序博客网 时间:2024/05/21 19:48

  (一):关于 iOS 的两种开源网络请求类库   

目前,在 iOS 以及 Mac应用中,使用较多的两种开源网络类库为 ASIHttpRequest和 AFNetworking.但是由于 ASIHttpRequest 已经停止更新,所以越来越多的开发者投入到了AFNetworking的使用和研究中。

         在 github 上,其地址为 https://github.com/AFNetworking/AFNetworking/tree/master#requirements,有关信息查阅请自行前往。

  

 (二):有关使用

        创建工程后,将 AFNetworking和UIKit+AFNetworking导入到项目中,并添加MobileCoreServices.framework、SystemConfiguration.framework、Security.framework框架。在需要使用的文件中,统一导入#import"AFNetworking.h"。   

       AFNetworking中,我们可以自行将其文件分为5个小类:

1:关于发起网络请求(AFURLConnectionOperation、AFHTTPRequestOperation、AFHTTPRequestOperationManager)

2:关于发起网络请求(其封装的 NSURLSession相关,需要 iOS7.0以后才支持,AFURLSessionManager、AFHTTPSessionManager)

3:关于请求及相应的序列化(AFURLRequestSerialization、AFURLResponseSerialization)

4:关于网络可到达性及连接状态发送改变(AFNetworkReachabilityManager)

5:关于加密(AFSecurityPolicy)。


a)发起一个GET 请求

/******************使用AFHTTPRequestOperationManager发送GET请求*****************/

    /*****

     - (AFHTTPRequestOperation *)GET:(NSString *)URLString

     parameters:(id)parameters

     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

    *****/

    //http://itunes.apple.com/lookup?id=794851407


    NSString *URLString = @"http://itunes.apple.com/lookup?id=794851407";

    //创建请求管理器

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];

    //设置请求管理器的请求和响应数据的格式

    manager.requestSerializer = [AFHTTPRequestSerializerserializer];

    manager.responseSerializer =[AFJSONResponseSerializerserializer];

    //发起 GET请求

    [managerGET:URLString parameters:nilsuccess:^(AFHTTPRequestOperation *operation,id responseObject){

       //请求成功回调

        NSLog(@"responseObject %@",responseObject);

    }failure:^(AFHTTPRequestOperation *operation,NSError *error){

        //请求失败回调

       NSLog(@"error is %d",[errorcode]);

    }];



b)发送一个POST1请求



  /******************使用AFHTTPRequestOperationManager发送POST1请求*****************/

    

    /*****

     - (AFHTTPRequestOperation *)POST:(NSString *)URLString

     parameters:(id)parameters

     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

    *****/

    

    NSString *URLString =@"http://itunes.apple.com/lookup";

    //构建请求的参数

   NSDictionary *para = @{@"id":@794851407};

    //获取请求管理器

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];

    //设置响应格式

    manager.responseSerializer = [AFJSONResponseSerializerserializer];

    //发起POST1请求

    [managerPOST:URLString parameters:parasuccess:^(AFHTTPRequestOperation *operation,id responseObject){

     //请求成功回调

        NSLog(@"operation.responseObject %@",operation.response);

       NSLog(@"responseObject %@",responseObject);

    }failure:^(AFHTTPRequestOperation *operation,NSError *error){

    //请求失败回调

   NSLog(@"errorcode %d",[errorcode]);

    }];


c)发送一个POST2请求

 /******************使用AFHTTPRequestOperationManager发送POST1请求*****************/

    

    /*****

    

- (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

    *****/

//获取请求管器
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);}];

d)使用AFHTTPRequestOperation发起请求

AFHTTPRequestOperation is a subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.

Although AFHTTPRequestOperationManager is usually the best way to go about making requests, AFHTTPRequestOperation can be used by itself.

AFHTTPRequestOperation是AFURLConnectionOperation 的子类,并使用HTTP or HTTPS协议发起请求。AFHTTPRequestOperation概括了关于请求的状态码和内容类型,决定了请求的成功与失败。

尽管AFHTTPRequestOperationManager是通常关于发起请求最好的方式,但AFHTTPRequestOperation对象也能通过自身发起请求。

GET with AFHTTPRequestOperation

NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];op.responseSerializer = [AFJSONResponseSerializer serializer];[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Error: %@", error);}];[[NSOperationQueue mainQueue] addOperation:op];
e)Batch of Operations(批量请求)

NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload) {    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];    }];    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];    [mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations) {    NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

f)网络检测及连接状态改变

1:

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));}];


2:

NSURL *baseURL = [NSURL URLWithString:@"http://example.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];            break;        case AFNetworkReachabilityStatusNotReachable:        default:            [operationQueue setSuspended:YES];            break;    }}];[manager.reachabilityManager startMonitoring];

0 0
原创粉丝点击