-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//[self getTest];

[self postTest];

}

-(void) getTest{

NSURLSession *session = [NSURLSession sharedSession];

NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"];

NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

NSLog(@"%d",data.length);

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

NSLog(@"%@",dict);

}];

[task resume];

}

-(void) postTest{

NSURLSession *session = [NSURLSession sharedSession];

//url = http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON

NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

request.HTTPMethod=@"POST";

request.HTTPBody = [@"username=123&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

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

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

NSLog(@"___%@",dict);

}];

[task resume];

}

- (void)downloadTask2
{
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; // 1.得到session对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; // 2.创建一个下载task
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url]; // 3.开始任务
[task resume]; // 如果给下载任务设置了completionHandler这个block,也实现了下载的代理方法,优先执行block
} #pragma mark - NSURLSessionDownloadDelegate
/**
* 下载完毕后调用
*
* @param location 临时文件的路径(下载好的文件)
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// location : 临时文件的路径(下载好的文件) NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致 NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; // 将临时文件剪切或者复制Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager]; // AtPath : 剪切前的文件路径
// ToPath : 剪切后的文件路径
[mgr moveItemAtPath:location.path toPath:file error:nil];
} /**
* 恢复下载时调用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{ } /**
* 每当下载完(写完)一部分时就会调用(可能会被调用多次)
*
* @param bytesWritten 这次调用写了多少
* @param totalBytesWritten 累计写了多少长度到沙盒中了
* @param totalBytesExpectedToWrite 文件的总长度
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"下载进度---%f", progress);
} #pragma mark ------------------------------------------------------------------
/**
* 下载任务:不能看到下载进度
*/
- (void)downloadTask
{
// 1.得到session对象
NSURLSession *session = [NSURLSession sharedSession]; // 2.创建一个下载task
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// location : 临时文件的路径(下载好的文件) NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; // 将临时文件剪切或者复制Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager]; // AtPath : 剪切前的文件路径
// ToPath : 剪切后的文件路径
[mgr moveItemAtPath:location.path toPath:file error:nil];
}]; // 3.开始任务
[task resume];
}

  

NSURLSession的用法的更多相关文章

  1. AFNetworking 3.0 源码解读(五)之 AFURLSessionManager

    本篇是AFNetworking 3.0 源码解读的第五篇了. AFNetworking 3.0 源码解读(一)之 AFNetworkReachabilityManager AFNetworking 3 ...

  2. iOS开发之网络编程--1、AFNetwork 3.x 的所有开发中常用基础介绍

    前言:第三方网络请求框架中AFNetwork 3.x收欢迎程度相当高的: 由于iOS 7 和 Mac OS X 10.9 Mavericks 中一个显著的变化就是对 Foundation URL 加载 ...

  3. (一二七)NSURLSession的基本用法 下载与数据获取

    简介 NSURLSession是苹果官方提供的一系列网络接口库,使用他们可以轻松实现下载和数据获取等任务.在上一篇文章中,我们介绍了使用NSURLConnection下载文件和断点续传的功能,实现起来 ...

  4. iOS开发之Alamofire源码解析前奏--NSURLSession全家桶

    今天博客的主题不是Alamofire, 而是iOS网络编程中经常使用的NSURLSession.如果你想看权威的NSURLSession的东西,那么就得去苹果官方的开发中心去看了,虽然是英文的,但是结 ...

  5. iOS网络学习之“远离NSURLConnection 走进NSURLSession”

    目前,在iOS的开发中,NURLConnection已经成为了过去式,现在的NSURLConnection已经deprected(iOS7之后),取而代之的是NSURLSession.而且AFNetw ...

  6. ios NSURLSession(iOS7后,取代NSURLConnection)使用说明及后台工作流程分析

    NSURLSession是iOS7中新的网络接口,它与咱们熟悉的NSURLConnection是并列的.在程序在前台时,NSURLSession与NSURLConnection可以互为替代工作.注意, ...

  7. AFNetworking 与 NSURLSession

    转载自:http://blog.sina.com.cn/s/blog_8157560c0101kt7h.html 1. 也就是说在IOS 7.1 之后你想用网络请求的话有两种途径,NSUrlSessi ...

  8. 【转载】NSURLSession教程

    原文:http://www.raywenderlich.com/51127/nsurlsession-tutorial 查理·富尔顿 2013年10月9日, 推特 注意从雷 :这是一个缩写版的一章 i ...

  9. NSURLSession 所有的都在这里(一)

    这篇文章会有什么? 在这篇文章中把NSURLSession.h文件集体梳理一遍,把里面的每个属性.代理和方法都拿出来说说,通过这篇文章我相信对于NSURLSession这一块的东西会梳理的比较全面一点 ...

随机推荐

  1. 部署spring boot + Vue遇到的坑(权限、刷新404、跨域、内存)

    部署spring boot + Vue遇到的坑(权限.刷新404.跨域.内存) 项目背景是采用前后端分离,前端使用vue,后端使用springboot. 工具 工欲善其事必先利其器,我们先找一个操作L ...

  2. 使用Magicodes.SwaggerUI快速配置SwaggerUI以及设置API分组

    Magicodes.SwaggerUI 快速配置和集成SwaggerUI 特点 通过配置文件简单配置即可完成SwaggerUI的API格式JSON生成和集成 支持API分组和隐藏 支持自定义页面和验证 ...

  3. Web for pentester_writeup之Directory traversal篇

    Web for pentester_writeup之Directory traversal篇 Directory traversal(目录遍历) 目录遍历漏洞,这部分有三个例子,直接查看源代码 Exa ...

  4. 智学网电脑端查分小工具 已更新V2.2

    特别鸣谢这段代码的源作者,我的大佬同学\(MetalkgLZH\).由于我没有做什么工作,这篇随笔基本不含相关技术细节. 再次强调,这个程序的主要部分由\(MetalkgLZH\)完成.技术细节与源码 ...

  5. 对pwntools生成的exp模版做了一些修改

    安装pwntools后,有一些命令行的工具可以用 ~ pwn template -h usage: pwn template [-h] [--host HOST] [--port PORT] [--u ...

  6. jieba分词基础知识

    安装:pip install jieba 导包:import jieba 精确模式:试图将句子最精确地切开,适合文本分析(很像人类一样去分词) jieba.cut(字符串) --> 返回生成器 ...

  7. P4873 [USACO14DEC] Cow Jog_Gold 牛慢跑(乱搞?二分?)

    (话说最近写的这类题不少啊...) 化简:给定数轴上一系列点,向正方向移动,点不能撞在一起,如果碰到一起就需要放到另外一行,求要多少行才能满足所有点不相撞的条件. (被标签误解,老是想到二分答案... ...

  8. 从Gartner IT Symposium,看RPA“一半是海水一半是火焰”

    2019年,艺赛旗和Gartner建立了咨询合作,并在企业发展策略中汲取了Gartner的部分建议.今年Gartner在全球召开了多场IT Symposium,并在Symposium发布2020的相关 ...

  9. drf

    跨域同源 django做跨域同源 需要把csrf去掉 跨站请求伪造 同源 同源机制:域名.协议.端口号相同的同源 简单请求 不写头部请求 跨域会拦截报错缺少请求信息 (1) 请求方法是以下三种方法之一 ...

  10. ASP.NET Core 1.0: Using Entity Framework Core

    伴随着ASP.NET Core 1.0发布的还有Entity Framework Core 1.0; 官方文档链接:https://docs.efproject.net/en/latest/platf ...