首页 > 代码库 > iOS AFNetworking 2.x JSON方法
iOS AFNetworking 2.x JSON方法
写在前面(废话,可略过)
正式开始
NSString *urlString = [NSStringstringWithFormat:@"xxxxxxxxxx"];//xxxx处写一个你的网址
//如果网址中有中文,需要转换
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//构建NSURL
NSURL *url = [NSURLURLWithString:urlString];
//构建请求,这个构建方法是基本构建方法的一个封装加强。主要多了超时属性,就是最后一个参数,4.0f。意思就是如果在4秒内没有响应,就不阻塞主线程(为啥放主线程就不赘述了)
NSURLRequest *request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:4.0f];
//以AF开始的是就是AFNetworking框架的API,这是1.x的方法。
AFJSONRequestOperation *op = [AFJSONRequestOperationJSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *dictionary = JSON;
int ret = [[dictionary objectForKey:@"ret"] intValue];
//对服务器返回数据进行判断
switch (ret) {
case -1:
[selfshowAlertWithString:@"用户未登录"];
break;
case 1:
[selfsaveDataToCurrentAccount];
[selfshowAlertWithDelegateWithString:@"保存成功"];
break;
case -2:
[selfshowAlertWithString:@"保存失败"];
break;
}
}failure:^(NSURLRequest *request,NSHTTPURLResponse *response, NSError *error, id JSON) {
[selfshowAlertWithString:[NSStringstringWithFormat:@"%@", error.localizedDescription]];
}];
[opstart];
NSString *urlString = [NSStringstringWithFormat:@"xxxxxxxx"];
//有中文,需要转换
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURLURLWithString:urlString];
NSURLRequest *request = [NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:4.0f];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperationalloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializerserializer];
[opsetCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject) {
NSDictionary *dictionary = responseObject;
int ret = [[dictionary objectForKey:@"ret"] intValue];
//对服务器返回数据进行判断
switch (ret) {
case -1:
[selfshowAlertWithString:@"用户未登录"];
break;
case 1:
[selfsaveDataToCurrentAccount];
[selfshowAlertWithDelegateWithString:@"保存成功"];
break;
case -2:
[selfshowAlertWithString:@"保存失败"];
break;
}
}failure:^(AFHTTPRequestOperation *operation,NSError *error) {
[selfshowAlertWithString:[NSStringstringWithFormat:@"%@", error.localizedDescription]];
}];
[[NSOperationQueuemainQueue] addOperation:op];
最后提提
iOS AFNetworking 2.x JSON方法