zoukankan      html  css  js  c++  java
  • iOS 网络请求 NSURLSession

    对于目前版本的系统的网络请求 网上很多东西都比较乱,现整理NSURLSession 的基本用法。

    //1.获取文件访问的路径   接口

        NSString *path=@"http://1.studyios.sinaapp.com/getAllClass.php";

        //2.封装 URL

        NSURL *url=[NSURL URLWithString:path];

        //3.创建请求命令

        NSURLRequest *request=[NSURLRequest requestWithURL:url];

    这是之前的老方法 NSURLConnection 

        //4.响应的对象

        __autoreleasing NSURLResponse *response;

        //5.错误信息

        __autoreleasing NSError *error;

      //*6.通过同步请求的方式 返回 data 对象  方法不能用 要用新方法

       NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

       //7.json解析

        NSArray *arrJson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

        NSLog(@"%@",arrJson);

    目前版本的NSURLSession 的一些基本用法

    //4.创建会话对象  通过单例方法实现的

        NSURLSession *session=[NSURLSession sharedSession];

        //5.执行会话任务 通过request请求 获取 data对象

        NSURLSessionDataTask *task= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)

        {

            //7.json解析

            NSArray *arrJson=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

            NSLog(@"%@",arrJson);

            

        }];

        //6.真正的执行任务  resume  继续

        [task resume];

  • 相关阅读:
    day60----日考
    css之单位
    如何装双系统win10下装Ubuntu
    css之Grid Layout详解
    css之position详解
    html+css的用户注册界面
    self-introduction
    ps常用操作
    前端基础之BOM和DOM
    emment语法
  • 原文地址:https://www.cnblogs.com/tmf-4838/p/5315915.html
Copyright © 2011-2022 走看看