zoukankan      html  css  js  c++  java
  • 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]; 
     
  • 相关阅读:
    Item2:建造者替代多参数构造器
    Java常量赋值失败?
    0828 列表 增删改查
    字符 列表的切片规则
    0820 字符转换为数字
    使用 in 判断是否有敏感词
    while循环
    for循环
    isalnum 判断变量是否由字符或者数字组成
    使用lower upper等字符大小写指令选择为大小写单词转换大小写
  • 原文地址:https://www.cnblogs.com/guiyangxueyuan/p/5315548.html
Copyright © 2011-2022 走看看