iOS AFNetworking 2.x JSON方法
写在前面(废话,可略过)
正式开始
NSString *urlString = [NSString stringWithFormat:@"xxxxxxxxxx"];//xxxx处写一个你的网址
//如果网址中有中文,需要转换
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//构建NSURL
NSURL *url = [NSURL URLWithString:urlString];
//构建请求,这个构建方法是基本构建方法的一个封装加强。主要多了超时属性,就是最后一个参数,4.0f。意思就是如果在4秒内没有响应,就不阻塞主线程(为啥放主线程就不赘述了)
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:4.0f];
//以AF开始的是就是AFNetworking框架的API,这是1.x的方法。
AFJSONRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *dictionary = JSON;
int ret = [[dictionary objectForKey:@"ret"] intValue];
//对服务器返回数据进行判断
switch (ret) {
case -1:
[self showAlertWithString:@"用户未登录"];
break;
case 1:
[self saveDataToCurrentAccount];
[self showAlertWithDelegateWithString:@"保存成功"];
break;
case -2:
[self showAlertWithString:@"保存失败"];
break;
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
[self showAlertWithString:[NSString stringWithFormat:@"%@", error.localizedDescription]];
}];
[op start];
NSString *urlString = [NSString stringWithFormat:@"xxxxxxxx"];
//有中文,需要转换
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:4.0f];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dictionary = responseObject;
int ret = [[dictionary objectForKey:@"ret"] intValue];
//对服务器返回数据进行判断
switch (ret) {
case -1:
[self showAlertWithString:@"用户未登录"];
break;
case 1:
[self saveDataToCurrentAccount];
[self showAlertWithDelegateWithString:@"保存成功"];
break;
case -2:
[self showAlertWithString:@"保存失败"];
break;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self showAlertWithString:[NSString stringWithFormat:@"%@", error.localizedDescription]];
}];
[[NSOperationQueue mainQueue] addOperation:op];
最后提提
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。