-(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. VB.NET 与 SAP RFC连接问题点

    与SAP RFC连接,电脑上必须要安装SAP软件,否则会报错ActiveX 输入工单号,无法带出SAP内接口RFC信息. 确认原因为:RFC接口需求的工单参数需要在前面加两位00,例如:1000541 ...

  2. Linux 命令行获取天气

    目标: 使用 Linux 命令行显示天气预报. 发行版: 所有 Linux 发行版. 要求: 能连上因特网的 Linux 难度: 容易 约定: # - 需要使用 root 权限来执行指定命令,可以直接 ...

  3. Go defer使用

    defer使用语法 //defer后面必须是函数调用语句或方法调用语句,不能是其他语句,否则编译器会出错. package main import ( "fmt" ) func f ...

  4. 石头剪刀步(rps):dp,概率&期望

    既然已经给std了,直接扔代码啦.代码注释还是不错哒. 因为我也有点懵,不明白的或有不同见解的一定要在评论区喷我啊! #include<bits/stdc++.h> using names ...

  5. noip模拟9 达哥随单题

    T1.随 看题第一眼,就瞄到最下面 孙金宁教你学数学  ?????原根?目测神题,果断跳过. 最后打了个快速幂,愉快的收到了达哥送来的10分. 实际上这题暴力不难想,看到一个非常小的mod应该就能想到 ...

  6. Python脚本之——API自动化框架总结

    学完了Python脚本接口自动化之后,一直没有对该框架做总结,今天终于试着来做一份总结了. 框架结构如下图: 来说一下每个目录的作用: Configs:该目录下存放的是.conf,.ini文件格式的配 ...

  7. 爬虫--requests爬取猫眼电影排行榜

    '''目标:使用requests分页爬取猫眼电影中榜单栏目中TOP100榜的所有电影信息,并将信息写入文件URL地址:http://maoyan.com/board/4 其中参数offset表示其实条 ...

  8. [LC]235题 二叉搜索树的最近公共祖先 (树)(递归)

    ①题目 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先. 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p.q,最近公共祖先表示为一个结点 x,满足 x 是 p.q 的祖先 ...

  9. MySql——创建数据表,查询数据,排序查询数据

    参考资料:<Mysql必知必会> 创建数据表 在学习前首先创建数据表和插入数据.如何安装mysql可以看看上个博客https://www.cnblogs.com/lbhym/p/11675 ...

  10. lufylegend.js教程(1)

    1.图片元素如何缩小? 在LSprite类中,有两个属性:{scaleX,scaleY},这两个属性属于按比例缩放精灵对象,可以放大,可以缩小,注意这两个属性是在图片中心点位置开始缩放. 代码: Bo ...