• 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]; 
     
  • 相关阅读:
    《构建之法》读书笔记⑤
    《构建之法》读书笔记④
    个人总结
    构建之法阅读笔记03
    构建之法阅读笔记02
    构建之法阅读笔记01
    第二阶段冲刺——seven
    第二阶段冲刺——six
    第二阶段冲刺——five
    第二阶段冲刺——four
  • 原文地址:https://www.cnblogs.com/guiyangxueyuan/p/5315548.html
Copyright © 2020-2023  润新知