1.NSURLSession使用模板

NSURLSession是苹果ios7后提供的api,用来替换 NSURLConnection
会话指的是程序和服务器的通信对象
//一.简单会话不可以配合会话(get请求)

- (void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];
//1.将字符串转化成URL字符串
strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; //2.用单列创建简单会话
NSURLSession *session = [NSURLSession sharedSession];
//3.会话任务(会话都是基于会话任务的)
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//页面交互放在主线程进行
dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}]; //4.新建任务默认是暂停的 要自己执行
[task resume];
}

//二.默认会话,可以对会话进行配置(GET)

- (void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"]; strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; //1.创建默认会话配置对象
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//2.1创建默认会话 (主线程中执行)
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//2.2不需要再次设置在主线程中执行
//dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
//});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}]; //3.执行会话任务
[task resume];
}

//三.默认会话 (POST)[和get的主要区别是NSMutableURLRequest]

- (void)startRequest
{
NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php";
NSURL *url = [NSURL URLWithString:strURL]; //1.构建NSMutableURLRequest对象
NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData]; //2.构建默认会话
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfig delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; //3.构建会话任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//dispatch_async(dispatch_get_main_queue(), ^{
[self reloadView:resDict];
//});
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}]; //4.执行会话任务
[task resume];
}

四.下载文件或图片,用的是下载会话任务(一般get post用的都是数据任务NSURLSessionDataTask)支持后台下载

//四.下载图片或文件,用会话下载任务NSURLSessionDownloadTask(支持后台下载)
- (IBAction)onClick:(id)sender
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/download.php?email=%@&FileName=test1.jpg", @"414875346@qq.com"];
NSURL *url = [NSURL URLWithString:strURL]; //1.构造默认会话 (基于委托代理非block回调模式)
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];//1.1主线程执行 //2.创建会话下载任务
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
//3.执行任务
[downloadTask resume];
} //4.实现回调接口,显示进度条
#pragma mark -- 实现NSURLSessionDownloadDelegate委托协议
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
//1.2 不用再次单独设置在主进程里进行
[_progressView setProgress:progress animated:TRUE];
NSLog(@"完成进度= %.2f%%", progress * 100);
NSLog(@"当前接收: %lld 字节 (累计已下载: %lld 字节) 期待: %lld 字节.", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
//5.下载完成时回调
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
//6.将临时文件保存到沙盒中
NSLog(@"临时文件: %@\\n", location); //6.1构建保存到沙盒的文件的路径
NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];
NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:@"test1.jpg"];
NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath]; //6.2如果已经存在先删除
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if ([fileManager fileExistsAtPath:downloadStrPath]) {
[fileManager removeItemAtPath:downloadStrPath error:&error];
if (error) {
NSLog(@"删除文件失败: %@", error.localizedDescription);
}
} //6.3将文件保存到沙盒中
error = nil;
if ([fileManager moveItemAtURL:location toURL:downloadURLPath error:&error]) {
NSLog(@"文件保存成功: %@", downloadStrPath);
UIImage *img = [UIImage imageWithContentsOfFile:downloadStrPath];
self.imageView1.image = img;
} else {
NSLog(@"保存文件失败: %@", error.localizedDescription);
}
}

2.AFNetwork使用模板(AFNetwork3 底层也是NSURLSession) <swift推荐用Alamofire>

//一.get请求(AFNetworking)

- (void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/mynotes/WebService.php?email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"]; strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; //1.默认配置
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//2.构建AF会话AFURLSessionManager (其实就是将NSURLSession对象换掉,其他函数接口都一样)
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
//3.构建AF生产的会话任务
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//3.1注意responseObject可以是字典或数组,不需要我们自己解析 NSLog(@"请求完成...");
if (!error) {
[self reloadView:responseObject];
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];
//4.执行任务
[task resume];
}

//二.post请求(AFNetworking)

- (void)startRequest
{
NSString *strURL = @"http://www.51work6.com/service/mynotes/WebService.php";
NSURL *url = [NSURL URLWithString:strURL]; //1.设置参数构建NSMutableURLRequest
NSString *post = [NSString stringWithFormat:@"email=%@&type=%@&action=%@", @"414875346@qq.com", @"JSON", @"query"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData]; //2.就NSMutableURLRequest对象不一样,其他都和get一样
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
//3.
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(@"请求完成...");
if (!error) {
[self reloadView:responseObject];
} else {
NSLog(@"error : %@", error.localizedDescription);
}
}];
//4.
[task resume];
}

//三.下载文件或图片(AFNetworking)<不用委托代理的模式,直接在block里处理>(既不是POST也不是GET)

- (IBAction)onClick:(id)sender
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.51work6.com/service/download.php?email=%@&FileName=test1.jpg", @"414875346@qq.com"]; NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //1.构建会话AFURLSessionManager
NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
//2.构建AF创建的会话下载任务
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
//3.设置进度条(需要设置在主线程进行)
NSLog(@"本地化信息=%@", [downloadProgress localizedDescription]);//完成百分比
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressView setProgress:downloadProgress.fractionCompleted animated:TRUE];
}); } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//4.指定文件下载好后的保存路径即可。不用自己操作(带返回参数的block)
NSString *downloadsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, TRUE) objectAtIndex:0];
NSString *downloadStrPath = [downloadsDir stringByAppendingPathComponent:[response suggestedFilename]];//4.1服务器端存储的文件名
NSURL *downloadURLPath = [NSURL fileURLWithPath:downloadStrPath]; return downloadURLPath; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//5.服务器返回数据后调用
NSLog(@"File downloaded to: %@", filePath);
NSData *imgData = [[NSData alloc] initWithContentsOfURL:filePath];
UIImage *img = [UIImage imageWithData:imgData];
self.imageView1.image = img; }];
//6.执行会话下载任务
[downloadTask resume];
}

//四.上传文件或图片(AFNetworking)(也用POST)

- (IBAction)onClick:(id)sender
{
_label.text = @"上传进度";
_progressView.progress = 0.0; NSString *uploadStrURL = @"http://www.51work6.com/service/upload.php";
NSDictionary *params = @{@"email" : @"414875346@qq.com"}; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test2" ofType:@"jpg"]; //1.构建NSMutableURLRequest(带上传文件对象)
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
URLString:uploadStrURL parameters:params
constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"file" fileName:@"1.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
//2.创建会话
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//3.创建会话上传任务(用AF构建)
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request
progress:^(NSProgress *uploadProgress) {
//3.1 上传进度条(主进程中显示)
NSLog(@"上传: %@", [uploadProgress localizedDescription]);
dispatch_async(dispatch_get_main_queue(), ^{
[_progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//3.2 上传完后操作
if (!error) {
NSLog(@"上传成功");
[self download];
} else {
NSLog(@"上传失败: %@", error.localizedDescription);
}
}];
//4.执行任务
[uploadTask resume];
}

NSURLSession使用模板和AFNetworking使用模板(REST风格)的更多相关文章

  1. JS 模板引擎之JST模板

    项目中有用到JST模板引擎,于是抽个时间出来,整理了下关于JST模板引擎的相关内容. 试想一个场景,当点击页面上列表的翻页按钮后,通过异步请求获得下一页的列表数据并在页面上显示出来.传统的JS做法是编 ...

  2. 30余套系统模版|DIV+CSS网页模板|简洁大气系统模板

    30余套系统模版|DIV+CSS网页模板|简洁大气系统模板.都是一些后台系统的模版,很适合开发一些管理系统,办公系统,网站后台系统等.使用很广泛,很实用的系统模版. 下载地址: 点击下载

  3. vs 2013下自定义ASP.net MVC 5/Web API 2 模板(T4 视图模板/控制器模板)

    vs 2013下自定义ASP.net MVC 5/Web API 2  模板(T4 视图模板/控制器模板): Customizing ASP.NET MVC 5/Web API 2 Scaffoldi ...

  4. C++模板学习:函数模板、结构体模板、类模板

    C++模板:函数.结构体.类 模板实现 1.前言:(知道有模板这回事的童鞋请忽视) 普通函数.函数重载.模板函数 认识. //学过c的童鞋们一定都写过函数sum吧,当时是这样写的: int sum(i ...

  5. 模板类的约束模板友元函数:template friend functions

    本来这篇博客是不打算写的,内容不是很难,对于我自己来讲,更多的是为了突出细节. 所谓template friend functions,就是使友元函数本身成为模板.基本步骤:1,在类定义的前面声明每个 ...

  6. C++—模板(1)模板与函数模板

    1.引入 如何编写一个通用加法函数?第一个方法是使用函数重载, 针对每个所需相同行为的不同类型重新实现这个函数.C++的这种编程机制给编程者极大的方便,不需要为功能相似.参数不同的函数选用不同的函数名 ...

  7. ES6模板字符串之标签模板

    首先,模板字符串和标签模板是两个东西. 标签模板不是模板,而是函数调用的一种特殊形式.“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数. 但是,如果模板字符串中有变量,就不再是简单的调用了,而 ...

  8. php实现下载模板与上传模板解析

    <? //下载模板的请求 if(isset($_GET['action']) && $_GET['action'] =='down_group_excel'){ $code = ...

  9. django之模板继承以和模板导入

    1,模板继承 一,模板继承 1.在template下面新建一个master.html的文件,当做母版. 2. 母版里需要被替代的部分,以block开始,以endblock结尾 {% block con ...

随机推荐

  1. java中list强转为map类型

    起因:读取数据库文件的测试用例,测试用例需要存放到一个map中,方便下次调用, 读取的内容返回的内容存放在一个list中,并且数据内容是key=value的形式,最开始使用切片方式,做了很多无用功,后 ...

  2. 【洛谷4149】[IOI2011] Race(点分治)

    点此看题面 大致题意: 给你一棵树,问长度为\(K\)的路径至少由几条边构成. 点分治 这题应该比较显然是点分治. 主要思路 与常见的点分治套路一样,由于\(K≤1000000\),因此我们可以考虑开 ...

  3. bazel安装

    https://blog.csdn.net/cxq234843654/article/details/70861155 sudo apt-get install openjdk-8-jdk echo ...

  4. python实现剑指offer删除链表中重复的节点

    题目描述 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针. 例如,链表1->2->3->3->4->4->5 处理后 ...

  5. React后台管理系统- rc-pagination分页组件封装

    1.用户列表页面使用的rc-pagination分页组件 Github地址: https://github.com/react-component/pagination 2.安装 cnpm insta ...

  6. servlet从服务器磁盘文件读出到浏览器显示,中文乱码问题,不要忘记在输入流和输出流都要设置编码格式,否则一个地方没设置不统一就会各种乱码

    package com.swift; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOE ...

  7. Pots POJ - 3414 (搜索+记录路径)

    Pots Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 22688   Accepted: 9626   Special J ...

  8. (78)zabbix值缓存(value cache)说明

    在zabbix-2.2版本之前,zabbix计算trigger与calculated/aggregate值都是直接通过sql语句查询并处理出来的结果,为了提高这块的性能与效率,zabbix引入了val ...

  9. js动态刷新时间

    <script type="text/javascript"> //取得系统当前时间 function getTime(){ var myDate = new Date ...

  10. ajax全局变量的使用

    var username; $.ajax({ type:"post", url:"a.action", data: {}, dataType: 'text',  ...