iOS 设计中 网络请求之 同步请求(json 请求--新方法和老方法)

//老的网络请求的方法-
 --NSData *data= [NSURLConnection sendSynchronousRequest:URlrequest returningResponse:&URLresponse error:&error];
代码实现:
 //1获取文件的访问路径
    NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";
    //2封装URL
    NSURL *URL=[NSURL URLWithString:path];
     //3创建请求命令
    NSURLRequest *URlrequest=[NSURLRequest requestWithURL:URL];
     //4响应的对象
   __autoreleasing NSURLResponse *URLresponse;
     //5错误信息
    __autoreleasing NSError *error;
     //6通过同步请求的方式 返回data的对象
      NSData *data= [NSURLConnection sendSynchronousRequest:URlrequest returningResponse:&URLresponse error:&error];
    //7json 请求
    NSArray *array=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    NSLog(@"%@",array);
 
 
 
//新的网络请求的方法
---NSURLSessionDataTask *task=[URlSession dataTaskWithRequest:URlrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
    }];
思路: 点击老方法sendSynchronousRequest: returningResponse: error:进入内库
找到[NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSession.h");
之后进入NSURLSession的内库 找到相应的方法;
 
代码实现:
 //1获取文件的访问路径
    NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";
    //2封装URL
    NSURL *URL=[NSURL URLWithString:path];
    //3创建请求命令
    NSURLRequest *URlrequest=[NSURLRequest requestWithURL:URL];
    //4创建会话对象  通过单例方法实现
    NSURLSession *URlSession=[NSURLSession sharedSession];
        //5执行会话的任务  通过request 请求 获取data对象
    NSURLSessionDataTask *task=[URlSession dataTaskWithRequest:URlrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //7json 解析
        NSArray *arrsession=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"%@",arrsession);
    }];
        //6真正的执行任务
    [task resume]; 
 
posted @ 2016-03-24 14:51  右手指尖轻轻触  阅读(414)  评论(0编辑  收藏  举报