-(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. Nmap的一些常用的nse脚本

    转自freebuf.com/  点击跳转 在这篇文章中,我们将研究最著名的渗透工具之一 Nmap 一款标志性的跨平台扫描器.它的原意为Network Mapper(网络映射器),具有相当强大的扫描功能 ...

  2. SSM配置后可以访问静态html文件但无法访问其他后台接口的解决方案

    web.xml中的一段 <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class> ...

  3. 使用Typescript重构axios(三十一)——添加axios.all和axios.spread方法

    0. 系列文章 1.使用Typescript重构axios(一)--写在最前面 2.使用Typescript重构axios(二)--项目起手,跑通流程 3.使用Typescript重构axios(三) ...

  4. 【Canvas真好玩】从黑客帝国开始

    前言 笔者之前有一段时间一直在学习Canvas相关的技术知识点,通过参考网上的一些资料文章,学着利用简单的数学和物理知识点实现了一些比较有趣的动画效果,最近刚好翻看到以前的代码,所以这次将这些代码实践 ...

  5. ELK分布式日志+NLog在.NetCore中的应用

    一.ELK简介 ELK是Elasticsearch.Logstash和Kibana首字母的缩写.这三者均是开源软件,这三套开源工具组合起来形成了一套强大的集中式日志管理平台 Elasticsearch ...

  6. 前端与算法 leetcode 48. 旋转图像

    目录 # 前端与算法 leetcode 48. 旋转图像 题目描述 概要 提示 解析 解法一:转置加翻转 解法二:在单次循环中旋转 4 个矩形 算法 传入测试用例的运行结果 执行结果 GitHub仓库 ...

  7. Docker 资源 | 官方文件

    Docker资源 Docker官方英文资源: docker官网:http://www.docker.com Docker windows入门:https://docs.docker.com/windo ...

  8. C++总结(1)keywords to the class

    目录 Chapter 1.关于类的关键字 1. class,struct与union 2.private,public与protected 3.friend 4.virtual 5.const 6.i ...

  9. 解决vue低版本安卓手机兼容性问题

    低版本的安卓手机可能会白屏,是由新特性不支持引起的 解决代码es6新特性兼容问题 1,npm 安装 npm install babel-polyfill npm install es6-promise ...

  10. SQL Server 2014:在修改表的内容时,提示“此单元格已更改,尚未将更改提交到数据库”,怎么处理?

    那一行上的属性为“不允许为null”的所有字段都填上对应信息,按回车键或者点击下一行任意一个单元格便会自动将更改的信息提交到数据库.