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. POJ 3187 Backward Digit Sums (递推,bruteforce)

    第1行j列的一个1加到最后1行满足杨辉三角,可以先推出组合数来 然后next_permutation直接暴. #include<cstdio> #include<iostream&g ...

  2. CUDA && GPU中dim3介绍

  3. C#自增运算符(++)

    一.C#自增运算符(++) 自增运算符(++)是将操作数加1. 1. 前缀自增运算符 前缀自增运算符是“先加1,后使用”.它的运算结果是操作数加1之后的值. 例如: ++x;  // 前缀自增运算符 ...

  4. MySql-8.0.12 安装教程随笔

    下载地址: https://www.mysql.com/downloads/ 现在最下边的社区版本,也就是免费版本 之后我们会看到有两个选择的下载,一个为zip压缩包格式,一个是Install版本,个 ...

  5. eclipse部署web项目至本地的tomcat但在webapps中找不到问题

    一.发现问题 在eclipse中新建Dynamic Web Project,配置好本地的tomcat并写好代码后选择Run on Server,但运行后发现在tomcat的安装目录下的webapps并 ...

  6. eclipse 导出Runnable JAR file ,双击无法执行原因与解决 双击后闪退的原因 批处理java打包文件 @echo off start javaw -jar *.jar

    eclipse 导出Runnable JAR file 导出后如果系统没有JRE,双击无法运行,需要用命令方法 安装后解决,如图 双击后闪退的原因,通过执行 java -jar TingGe.jar ...

  7. 可拖拽div

    在开发的时候需要一个可拖拽的prompt弹框.自己写了一个,大概思路为: 1.获取鼠标左键按下移动的起点坐标(x,y). 2.获取div的left和top属性. 3.得到鼠标坐标到左上角的距离(x-t ...

  8. 使用vscode开发vue cli 3项目,配置eslint以及prettier

    初始化项目时选择eslint-config-standard作为代码检测规范,vscode安装ESLint和Prettier - Code formatter两个插件,并进行如下配置 { " ...

  9. 最新Python3.6从入门到高级进阶实战视频教程

    点击了解更多Python课程>>> 最新Python3.6从入门到高级进阶实战视频教程 第1篇 Python入门导学 第2篇 Python环境装置 第3篇 了解什么是写代码与Pyth ...

  10. 04.VUE学习之v-text v-html

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...