NSURLSession使用模板和AFNetworking使用模板(REST风格)
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风格)的更多相关文章
- JS 模板引擎之JST模板
项目中有用到JST模板引擎,于是抽个时间出来,整理了下关于JST模板引擎的相关内容. 试想一个场景,当点击页面上列表的翻页按钮后,通过异步请求获得下一页的列表数据并在页面上显示出来.传统的JS做法是编 ...
- 30余套系统模版|DIV+CSS网页模板|简洁大气系统模板
30余套系统模版|DIV+CSS网页模板|简洁大气系统模板.都是一些后台系统的模版,很适合开发一些管理系统,办公系统,网站后台系统等.使用很广泛,很实用的系统模版. 下载地址: 点击下载
- 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 ...
- C++模板学习:函数模板、结构体模板、类模板
C++模板:函数.结构体.类 模板实现 1.前言:(知道有模板这回事的童鞋请忽视) 普通函数.函数重载.模板函数 认识. //学过c的童鞋们一定都写过函数sum吧,当时是这样写的: int sum(i ...
- 模板类的约束模板友元函数:template friend functions
本来这篇博客是不打算写的,内容不是很难,对于我自己来讲,更多的是为了突出细节. 所谓template friend functions,就是使友元函数本身成为模板.基本步骤:1,在类定义的前面声明每个 ...
- C++—模板(1)模板与函数模板
1.引入 如何编写一个通用加法函数?第一个方法是使用函数重载, 针对每个所需相同行为的不同类型重新实现这个函数.C++的这种编程机制给编程者极大的方便,不需要为功能相似.参数不同的函数选用不同的函数名 ...
- ES6模板字符串之标签模板
首先,模板字符串和标签模板是两个东西. 标签模板不是模板,而是函数调用的一种特殊形式.“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数. 但是,如果模板字符串中有变量,就不再是简单的调用了,而 ...
- php实现下载模板与上传模板解析
<? //下载模板的请求 if(isset($_GET['action']) && $_GET['action'] =='down_group_excel'){ $code = ...
- django之模板继承以和模板导入
1,模板继承 一,模板继承 1.在template下面新建一个master.html的文件,当做母版. 2. 母版里需要被替代的部分,以block开始,以endblock结尾 {% block con ...
随机推荐
- HTTP 请求方法介绍
浏览器从 web 服务器(或者叫应用服务器)上使用 HTTP 协议下载网站,HTTP 协议是基于一种 请求-响应(request-response)模型的.客户端(你的浏览器)从运行在物理机器上的 w ...
- 问题 F: 等比数列
问题 F: 等比数列 时间限制: 1 Sec 内存限制: 64 MB提交: 2699 解决: 1214[提交][状态][讨论版][命题人:外部导入] 题目描述 已知q与n,求等比数列之和: 1+q ...
- springboot集成shiro的session污染问题
问题起因是这样的,有两套系统,系统a和系统b.两套系统均使用shiro做的权限管理,之前部署在两台机器上.使用浏览器打开a系统后另开页签打开b系统,互不干扰都能正常使用,后因业务迁移,两套系统部署到了 ...
- Debug与Release版本的区别详解
原文链接 Debug 和 Release 并没有本质的区别,他们只是VC预定义提供的两组编译选项的集合,编译器只是按照预定的选项行动.如果我们愿意,我们完全可以把Debug和Release的行为完全颠 ...
- 去除myeclipse中doget和dopost方法中的注释
当我们使用myeclipse新建servlet时发现doget和dopost方法中有一些无用的注释,每次新建一个servlet时都要手动删除特别麻烦. 下面就教大家如何去除这些注释! 以myeclip ...
- react的redux无状态组件
Provider功能主要为以下两点: 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件 接收Redux的store作为props,通过context对象传递给子孙组件上的connec ...
- 【C++学习笔记】 链式前向星
链式前向星是一种常见的储存图的方式(是前向星存图法的优化版本),支持增边和查询,但不支持删边(如果想要删除指定的边建议用邻接矩阵). 储存方式 首先定义数组 head[ i ] 来储存从节点 i 出发 ...
- 洛谷P1164小A点菜
这也是一道01背包的题 用的方法比较的巧妙.这个动态规划相当于反过来做的,自己理解就知道了.代码很短 #include<bits/stdc++.h> using namespace std ...
- Centos7 PHP的安装和配置
前面Nginx和httpd的安装都是为了支持PHP而弄的,然后这个目标就给了我一沉重的打击,等我慢慢道来,先来说说PHP的安装和配置吧. 一.PHP的安装 1.由于linux的yum源不存在php7. ...
- git 命令汇总
本地库处理 git init 初始化仓库 git clone [地址] 下载项目 git status 查看当前暂存等状态 git add 添加暂存 cat .git/config 查看git配置 l ...