码迷,mamicode.com
首页 > Web开发 > 详细

AFNetworking使用

时间:2015-04-03 13:20:50      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

//Get请求数据

+ (void)get:(NSString *)urlStr params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure

{

        // 1.获得请求管理者

        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

        NSString *URL = [NSString stringWithFormat:@"%@%@",HOST,urlStr];

        NSLog(@"%@",URL);

        // 2.发送GET请求

        [mgr GET:URL parameters:params

        success:^(AFHTTPRequestOperation *operation, id responseObj) {

            if (success) {

                success(responseObj);

            }

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

            if (failure) {

                failure(error);

            }

        }];

}

 

//Post请求数据

+ (void)post:(NSString *)urlStr params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure

{

    if ([[self class] checkNetworkState]) {

        //获取公用参数

        NSMutableDictionary *requestParms = [[self class] publicParms];

        if (params!=nil) {

            //不为空 合并字典,公共参数字典

            [requestParms addEntriesFromDictionary:params];

        }

        //1.获得请求管理者

        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

    /********这里很重要********/

        //1.mgr.responseSerializer = [AFJSONResponseSerializer serializer];

        //2.mgr.requestSerializer = [AFJSONRequestSerializer serializer];

        //3.mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

 

        NSString *URL = [NSString stringWithFormat:@"%@%@",HOST,urlStr];

        NSLog(@"当前接口URL==%@",URL);

        NSLog(@"当前接请求的 参数 ==%@",requestParms);

        // 2.发送POST请求

        [mgr POST:URL parameters:requestParms success:^(AFHTTPRequestOperation *operation, id responseObj) {

            

            success(responseObj);

            

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

            

            failure(error);

            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

            NSLog(@"底层失败 ==error ==%@",[error localizedDescription]);

            [MBProgressHUD showError:@"网络不给力,稍后再试" toView:[UIApplication sharedApplication].keyWindow];

            

        }];

        

    }else{

        

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

        [MBProgressHUD showError:@"网络已断开,请检查网络连接" toView:[UIApplication sharedApplication].keyWindow];

        failure(nil);

        

    }

}

AFNetworking使用

标签:

原文地址:http://www.cnblogs.com/xinghuo/p/4389602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!