·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> AFNetworking使用

AFNetworking使用

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

//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);

        

    }

}