ios处理网络请求,用的比较多的是第三方工具类AFNetworking,因为原生的比较麻烦。
如登录时发送账号跟密码跟后台比对,过程如下,后台返回的是json,如
{"login":{"id":"0001","status":"OK","errorMsg":""}}
下面是使用时的举例。
复制代码
1 #import "AFNetWorking.h"
2
3 NSString urlLogin = @"www.xxx.com";
4 //创建请求管理器
5 AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
6 //申明请求的数据为text/html型
7 requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
8 requestManager.requestSerializer.HTTPShouldHandleCookies = YES;
9 [requestManager GET:urlLogin
10 parameters:nil
11 success:^(AFHTTPRequestOperation *operation, id responseObject) {
12 NSDictionary *dict = responseObject[@"login"];
13 NSString *str = [dict objectForKey:@"status"];
14 NSString *errorMsg = [dict objectForKey:@"errorMsg"];
15 //如果比对成功,就跳往下个页面
16 if (str && [str isEqualToString:@"OK"]) {
17 MSTabBarViewController *tabBar = [[MSTabBarViewController alloc] init];
18 [self presentViewController:tabBar animated:YES completion:nil];
19 } else {
20 //比对不成功,弹出提示
21 self.alertView = [[UIAlertView alloc]initWithTitle:@"" message:errorMsg delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"ok", nil];
22 [self.alertView show];
23 }
24
25 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
26 NSLog(@"服务器出错");
27 }];
复制代码
当然前提是得引入AFNetWorking的文件。
上述都是前台从服务器接受数据,若想把数据往后台传,比如json。可以使用ios自带的方法,也不知什么原因,用afneetworking传不了。
json格式如下:
复制代码
{
"list":
[
{"tel":"189XXXXXXX1", "name":""},
{"tel":"189XXXXXXX2", "name":""},
{"tel":"189XXXXXXX3", "name":""}
]
}
复制代码
然后拼写json时可以用
复制代码
-(void)formatAllContacts{
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (ZMOrdinaryContactsModel *ordinary in self.totalContact) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:ordinary.phoneNum forKey:@"tel"];
[dic setObject:ordinary.userName forKey:@"name"];
[arr addObject:dic];
}
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:arr,@"list", nil];
self.contactsToMeetDict = dic1;
}
复制代码
在model中发送请求可以用
复制代码
- (void)makeRequest:(ZMHomeViewController *)homeController
{
// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http:xxx.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 2.设置请求头
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// NSData --> NSDictionary
// NSDictionary --> NSData
//homeController.contactsToMeetDict即为要发往后台的字典
NSData *data = [NSJSONSerialization dataWithJSONObject:homeController.contactsToMeetDict options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = data;
// 4.发送请求
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"发送JSON成功");
}];
}