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. BZOJ 1229: [USACO2008 Nov]toy 玩具

    BZOJ 1229: [USACO2008 Nov]toy 玩具 标签(空格分隔): OI-BZOJ OI-三分 OI-双端队列 OI-贪心 Time Limit: 10 Sec Memory Lim ...

  2. Quartz 配置文件属性

    主要配置 Property Name Req'd Type Default Value org.quartz.scheduler.instanceName no string 'QuartzSched ...

  3. zabbix告警时间和恢复时间相同的解决方法

    出现原因:在动作,恢复操作中,恢复时间成了{EVENT.DATE} {EVENT.TIME},所以和告警时间相同. 解决方法:将{EVENT.DATE}{EVENT.TIME}改成{EVENT.DAT ...

  4. 洛谷P2468 [SDOI2010]粟粟的书架(二分答案 前缀和 主席树)

    题意 题目链接 给出一个矩形,每个点都有一些值,每次询问一个子矩阵最少需要拿几个数才能构成给出的值 Sol 这题是真坑啊.. 首先出题人强行把两个题拼到了一起, 对于前$50 \%$的数据,考虑二分答 ...

  5. GNU汇编 程序状态字访问指令

    .text .global  _start _start: mrs r0,cpsr orr r0,#0b100 msr cpsr,r0

  6. 【IDEA】热部署插件Jrebel破解安装

    JRebel 介绍 IDEA上原生是不支持热部署的,一般更新了 Java 文件后要手动重启 Tomcat 服务器,才能生效,浪费不少生命啊.目前对于idea热部署最好的解决方案就是安装JRebel插件 ...

  7. 【Ecshop】后台菜单与权限管理

    主要php文件: 1,admin/includes/inc_menu.php ECSHOP管理中心菜单数组--配置菜单组及URL 2,languages/zh_cn/admin/common.php  ...

  8. php扩展开发-快速上手

    系统环境CentOS release 6.5 (Final) PHP版本php-5.6.27 扩展开发需要有php环境及php的源代码,我的PHP安装目录/home/zhangxiaomin/stud ...

  9. Python知识点入门笔记——特色数据类型(元组)

    元组(tuple)是Python的另一种特色数据类型,元组和列表是相似的,可以存储不同类型的数据,但是元组是不可改变的,创建后就不能做任何修改操作. 创建元组 用逗号隔开的就是元组,但是为了美观和代码 ...

  10. MongDB之各种查询操作

    接口IMongDaoFind: package com.net.test.mongdb.dao; public interface IMongDaoFind { public void findUse ...