获取网络数据请求

写了几种获取网络数据的方式和下载任务的方式
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;
    
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容