iOS开发Google Protocol Buffer 的解析封装(二)

为此我封装了一个Google Protocol Buffer的网络解析方法,由于项目时间比较急,我没有写出更好的封装方法,我会继续创作,希望大家的鼓励与支持。

PBHttpMethod.h 的文件

#import 
@interface PBHttpMethod : NSObject
+(void)postDataByString:(NSString *)urlString BODYData:(NSData *)bodyData WithDataBlock:(void (^)(id data))dataBlock WithResponseBlock:(void (^)(NSURLResponse *response))responseBlock WithErroBlock:(void (^)(NSError *error))errorBlock;
@end

PBHttpMethod.m 的文件

#import "PBHttpMethod.h"
#import 
#import "ApiM.pb.h"
@implementation PBHttpMethod
+ (void)postDataByString:(NSString *)urlString BODYData:(NSData *)bodyData WithDataBlock:(void (^)(id))dataBlock WithResponseBlock:(void (^)(NSURLResponse *))responseBlock WithErroBlock:(void (^)(NSError *))errorBlock{
*//URL的汉字字符串转码*
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:30];
[request setAllHTTPHeaderFields:nil];
[request setHTTPBody:bodyData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 输出返回的状态码,请求成功的话为200 /* 输出http响应的状态码 */
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger responseStatusCode = [httpResponse statusCode];
NSLog(@"输出http响应的状态码 %ld", responseStatusCode);
if (responseStatusCode == 200) {
if (error) {
NSLog(@"网络请求失败-<<<<<%@",error);
errorBlock(error);//错误回调
} else {
dataBlock(data);//成功获取实体的回调数据
}
}else{
NSLog(@"服务器异常");
responseBlock(response);//服务器异常的回调数据
}
}];
[task resume];
}
@end

你可能感兴趣的:(iOS,iOS)