关闭

AFNetworking NSURLConnect 到NSURLSession

302人阅读 评论(0) 收藏 举报
分类:

转自:http://my.oschina.net/u/2252300/blog/615951

最近更新了AFNetworking的版本,用了最新的3.0.4

发现较之前使用的2.5版本有较大的区别

在文件目录结构上3.0.4去除了NSURLConnection这个文件夹和里面的

AFHTTPRequestOperation.h
AFHTTPRequestOperation.m
AFHTTPRequestOperationManager.h
AFHTTPRequestOperationManager.m
AFURLConnectionOperation.h
AFURLConnectionOperation.m
这6个文件

在之前的2.5版本中我们常使用的方法是:
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
mgr.responseSerializer = [AFJSONResponseSerializer serializer];

NSDictionary *params = @{ @"PPID":[NSString stringWithFormat:@"%ld", (long)ppId],
@"UserID":userId,
};

[mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* jsonRsp = (NSDictionary *)responseObject;
if (isSuccessRsp(jsonRsp))
{
success(jsonRsp);
}
else
{
failure(errorMsgRsp(jsonRsp));
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error.description);
}];

- (AFHTTPRequestOperation *)POST:(NSString *)URLString
headParameters:(id)headParameters
bodyParameters:(id)bodyParameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
[self setHeadParameters:headParameters];

NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString] absoluteString] parameters:bodyParameters error:nil];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];

[self.operationQueue addOperation:operation];

return operation;
}
同时也不需要手动写队列

现3.0.4使用方法更加简单
- (void)POST:(NSString *)URLString
headParameters:(id)headParameters
bodyParameters:(id)bodyParameters
success:(void (^)( id responseObject))success
failure:(void (^)( NSError *error))failure
{
NSURL *url= [NSURL URLWithString:URLString];
if (url == NULL)
{
return;
}

AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];

if (headParameters)
{
[self setHeadParameters:headParameters sessionMgr:sessionManager];
}

[sessionManager POST:[url absoluteString] parameters:bodyParameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12603次
    • 积分:371
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:21篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论