iOS 网络请求

方法一.NSURLConnection

 1 //1.获取文件访问的路径
 2     NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";
 3     //2.封装URL
 4     NSURL *url=[NSURL URLWithString:path];
 5     //3.创建请求命令
 6     NSURLRequest *request=[NSURLRequest requestWithURL:url];
 7     //4.响应的对象
 8     __autoreleasing NSURLResponse *response;
 9     //5.错误信息
10     __autoreleasing NSError *error;
11     //6.通过同步请求的方式 返回data对象
12     NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
13     //7.json解析
14     NSArray *arrjson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
15     NSLog(@"%@",arrjson);

方法二.NSURLSession,上面方法在ios9.0之前就会发生警告了,现在为大家分享一下新版本的方法

 1 //1.获取文件访问的路径
 2     NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";
 3     //2.封装URL
 4     NSURL *url=[NSURL URLWithString:path];
 5     //3.创建请求命令
 6     NSURLRequest *request=[NSURLRequest requestWithURL:url];
 7     //4.创建会话对象,通过单例方法实现
 8     NSURLSession *session=[NSURLSession sharedSession];
 9     //5.执行会话任务 通过request请求 获取data对象
10     NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
11         //7.json解析
12         NSArray *arrjson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
13         NSLog(@"%@",arrjson);
14 
15     }];
16     //6.真正的执行任务
17     [task resume];
原文地址:https://www.cnblogs.com/zhaochaobin/p/5317357.html