美文网首页ios
获取网络数据请求

获取网络数据请求

作者: hunterzhu | 来源:发表于2016-08-10 21:25 被阅读235次

写了几种获取网络数据的方式和下载任务的方式
1.普通的request请求,block回调数据

    {
    /*******************普通request的请求,利用block接收*******************/
    //1.获取资源
    NSURL *url = [NSURL URLWithString:@"http://news-at.zhihu.com/api/3/news/latest"];
    //2.获取请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    //4.添加任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //错误检查
        if (error != 0) {
            NSLog(@"请求失败%@",error);
        }else {
            //状态码,响应头内容
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSInteger status = httpResponse.statusCode;
            NSDictionary *headerDic = httpResponse.allHeaderFields;
            NSLog(@"status = %ld , headerFields = %@",status,headerDic);
            //获取json数据
            id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"json = %@",jsonData);
        }
    }];
    //5.发起任务 resume - 恢复
    [dataTask resume];
    }

2.自定义请求,block回调数据

    /*******************自定义request的请求,利用block接收*******************/
    NSURL *url = [NSURL URLWithString:@"http://piao.163.com/m/cinema/list.html?apiVer=6&city=110000"];
    //创建可变Request对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //缓存策略
    request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    //超时设置
    request.timeoutInterval = 120;
    //请求方式(默认是get)
    request.HTTPMethod = @"POST";//这里的必须大写
    //设置请求头   Accept-Language
    [request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
    
    //session(默认是异步)
    NSURLSession *session = [NSURLSession sharedSession];
    
    //添加任务(block)
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //错误检查
        if (error != nil) {
            NSLog(@"请求失败%@",error);
        }else {
            //状态码,响应头内容
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSInteger status = httpResponse.statusCode;
            NSDictionary *headerDic = httpResponse.allHeaderFields;
            NSLog(@"status = %ld , headerFields = %@",status,headerDic);
            //获取json数据
            id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"json = %@",jsonData);
        }
    }];
    
    [dataTask resume];
    

3.自定义session的方式,代理方式
代理方法:

NSURLSessionDataDelegate

内容:

   /*******************自定义session,利用代理接收*******************/
    
    NSURL *url = [NSURL URLWithString:@"http://news-at.zhihu.com/api/3/news/latest"];
    //设置请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //请求方式是get
    [request setHTTPMethod:@"GET"];
    
    
    //自定义session
    //设置session的配置
    //+defaultSessionConfiguration  用于创建默认类型的Session对象
    //+ephemeralSessionConfiguration 用于创建临时类型的Session对象
    //+backgroundSessionConfiguration:(NSString *)identifier  用于创建后台Session对象
    //identifier:作用标示后台的session,做好和app的bundle id相同
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //缓存策略
    config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
    //蜂窝数据
    config.allowsCellularAccess = YES;
    /*
     sessionWithConfiguration:session配置
     delegate:代理 NSURLSessionDataDelegate
     delegateQueue:代理队列 (主队列)
     */
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //直接获取请求,因为是代理方式
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    //resume
    [dataTask resume];

代理方法:

#pragma makr- 代理方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    //响应头
    NSLog(@"response : %@",response);
    //必须写这句话继续接收响应体
    //(block的回调)
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
 
    id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"heehhee");
    NSLog(@"json - %@",jsonData );
    
}

4.下载一张图片

- (IBAction)nomalDownLoad:(UIButton *)sender {
    //获取一个路径 ,一张图片
    NSURL *url = [NSURL URLWithString:@"http://www.pptbz.com/pptpic/UploadFiles_6909/201204/2012041411433867.jpg"];
    NSURLSession *session = [NSURLSession sharedSession];
    //不设置request请求头,使用默认的
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //打印一下下载到的路径
        //因为这个路径是一个临时文件所以需要把下载的东西移动到另外一个地方
        NSLog(@"位置:%@",location);
        //移动文件
        NSFileManager *manager = [NSFileManager defaultManager];
        NSString *newPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/download.jpg"];
        NSURL *newURL = [NSURL fileURLWithPath:newPath];
        [manager moveItemAtURL:location toURL:newURL error:nil];
        NSLog(@"newURL : %@",newURL);
        //图片就保存在了本地了
        
    }];
    [task resume];
    
}

5.下载一部电影,用进度条查看进度
头文件

    __weak IBOutlet UIProgressView *progressView;
    NSURLSessionDownloadTask *downTask;
    //下载好的数据存起来
    NSData *saveData;
    
    NSURLSession *startSession;

这里使用的代理是

NSURLSessionDownloadDelegate

//能暂停的任务
- (IBAction)startDownLoad:(UIButton *)sender {
    
    NSURL *url = [NSURL URLWithString:@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4"];
    //填写一个配置
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //用代理来写,全局变量
    startSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //建立一个下载任务,全局变量
    downTask = [startSession downloadTaskWithURL:url];
    //开始
    [downTask resume];
    
    
}

- (IBAction)pause:(UIButton *)sender {
    //暂停下载
    [downTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {//已经下载好的数据
  //定义一个全局变量来接收,在后面需要恢复下载
        saveData = resumeData;
        //安全释放
        downTask = nil;    
    }];
    
}

//恢复下载
- (IBAction)going:(UIButton *)sender {
    //这里的downtask已经不是之前的downtask了
    //恢复到已经下载的数据
    downTask = [startSession downloadTaskWithResumeData:saveData];
    //继续任务
    [downTask resume];
    
}


//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSLog(@"location:%@",location);
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *newPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/01.mp4"];
    NSURL *newURL = [NSURL URLWithString:newPath];
    [manager moveItemAtURL:location toURL:newURL error:nil ];
    
    NSLog(@"newURL:%@",newPath);
    
}

//每下载一个数据包调用一次
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    /*
     bytesWritten   -每次下载的数据包的大小
     totalBytesWritten -已下载的数据
     totalBytesExpectedToWrite  -总数据大小
     */
    
    NSLog(@"bytesWritten %lld , totalBytesWritten  %lld,totalBytesExpectedToWrite %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    //进度条
    float current = (float)totalBytesWritten /totalBytesExpectedToWrite;
    progressView.progress = current;
    
}

相关文章

  • 获取网络数据请求

    写了几种获取网络数据的方式和下载任务的方式1.普通的request请求,block回调数据 2.自定义请求,blo...

  • 网络基础

    获取网络数据 python中使用第三方库requests来获取网络数据import requests 确定请求的地...

  • 4.获取数据并赋值

    url封装 网络请求封装 首页获取数据并展示

  • iOS-Contacts( TableView)

    [ ] 准备阶段:数据层model​ 请求数据-ContactsService ​ 写一个mock网络请求获取JS...

  • JSON数据获取和解析

    AFNetWorking对网络数据post请求获取数据步骤 1.创建“AFHTTPRequestOperation...

  • 2w爬虫课程总结笔记

    爬虫 模拟客户端发起网络请求,获取网络数据只要客户端能够获取的数据,爬虫都能获取 获取流程: 1.确定目标网站,分...

  • 01第一个iOS程序

    开发步骤 搭建基本的软件界面 UI (User Interface) 获取网络数据 网络请求,JSON 显示数据到...

  • iOS学习笔记12-网络(一)NSURLConnection

    一、网络请求 在网络开发中,需要了解一些常用的请求方法: GET请求:get是获取数据的意思,数据以明文在URL中...

  • 网络请求优化

    网络优化,首先要考虑网络请求有哪些过程,组拼数据------> 封装请求发起请求--->DNS获取ip-->通过h...

  • 关于Xcode 8.0网络请求崩溃记录

    一 .unrecognized selector sent to instance 网络请求,获取到的JSON数据...

网友评论

    本文标题:获取网络数据请求

    本文链接:https://www.haomeiwen.com/subject/gipjsttx.html