iOS异步下载下载进度条显示
说到http异步下载,首先要知道其中的关键类。
关键类是NSURLConnection NSURLRequest NSMutableURLRequest
委托是 NSURLConnectionDownloadDelegate NSURLConnectionDataDelegate NSURLConnectionDelegate
首先,我们要实现最基本的下载功能。
LQAsynDownload.h

//
// LQAsynDownload.h
// lgTest
//
// Created by yons on 14-2-14.
// Copyright (c) 2014年 GQ. All rights reserved.
// #import <Foundation/Foundation.h> @interface LQAsynDownload : NSObject<NSURLConnectionDataDelegate> @property (strong) NSURL *httpURL; + (LQAsynDownload *) initWithURL:(NSURL *) url; - (void) startAsyn; @end

LQAsynDownload.m

//
// LQAsynDownload.m
// lgTest
//
// Created by yons on 14-2-14.
// Copyright (c) 2014年 GQ. All rights reserved.
// #import "LQAsynDownload.h" @interface LQAsynDownload() @property (assign) long long contentLength; @property (assign) long long receiveLength; @property (strong) NSMutableData *receiveData; @property (strong) NSString *fileName; @property (strong) NSURLConnection *theConnection; @property (strong) NSURLRequest *theRequest; @end @implementation LQAsynDownload @synthesize receiveData = _receiveData, fileName = _fileName,
theConnection=_theConnection, theRequest=_theRequest; + (LQAsynDownload *) initWithURL:(NSURL *) url{
LQAsynDownload *asynDownload = [[LQAsynDownload alloc] init];
asynDownload.theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
return asynDownload;
} - (void) startAsyn{
_contentLength=0;
_receiveLength=0;
self.receiveData = [[NSMutableData alloc] init];
self.theConnection = [[NSURLConnection alloc] initWithRequest:self.theRequest delegate:self];
} //接收到http响应
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
_contentLength = [response expectedContentLength];
_fileName = [response suggestedFilename];
NSLog(@"data length is %lli", _contentLength);
} //传输数据
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
_receiveLength += data.length;
[_receiveData appendData:data];
NSLog(@"data recvive is %lli", _receiveLength);
} //错误
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self releaseObjs];
NSLog(@"%@",error.description);
} - (void) releaseObjs{
self.receiveData = nil;
self.fileName = nil;
self.theRequest = nil;
self.theConnection = nil;
} //成功下载完毕
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
//数据写入doument
//获取完整目录名字
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory, _fileName];
//创建文件
[_receiveData writeToFile:savePath atomically:YES];
[self releaseObjs];
} @end

最简单的功能调用代码:
LQAsynDownload *dwn = [LQAsynDownload initWithURL:[[NSURL alloc] initWithString:@"http://t2.baidu.com/it/u=0,3067863433&fm=19&gp=0.jpg"]];
[dwn startAsyn];
查查模拟器,神啊,MM靓图出现了

情人节努力的补充礼物,哈哈。

关键点分析:
其实就是实现NSURLConnectionData委托的几个方法:
这个方法是客户端接收到回应后的调用方法,算是下载的开始。
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
跟着就是接收数据的方法
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
还有一个遇到错误时的处理方法
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
最后是下载成功调用的方法
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
接着实现,下载进度查看。
在原代码基础上增加2个block 属性。
LQAsynDownload.h

1 //
2 // LQAsynDownload.h
3 // lgTest
4 //
5 // Created by yons on 14-2-14.
6 // Copyright (c) 2014年 GQ. All rights reserved.
7 //
8
9 #import <Foundation/Foundation.h>
10
11 typedef void (^initProgress)(long long initValue);
12
13 typedef void (^loadedData)(long long loadedLength);
14
15 @interface LQAsynDownload : NSObject<NSURLConnectionDataDelegate>
16
17 @property (strong) NSURL *httpURL;
18
19 @property (copy) void (^initProgress)(long long initValue);
20
21 @property (copy) void (^loadedData)(long long loadedLength);
22
23 + (LQAsynDownload *) initWithURL:(NSURL *) url;
24
25 - (void) startAsyn;
26
27 @end

LQAsynDownload.m

1 //
2 // LQAsynDownload.m
3 // lgTest
4 //
5 // Created by yons on 14-2-14.
6 // Copyright (c) 2014年 GQ. All rights reserved.
7 //
8
9 #import "LQAsynDownload.h"
10
11 @interface LQAsynDownload()
12
13 @property (assign) long long contentLength;
14
15 @property (assign) long long receiveLength;
16
17 @property (strong) NSMutableData *receiveData;
18
19 @property (strong) NSString *fileName;
20
21 @property (strong) NSURLConnection *theConnection;
22
23 @property (strong) NSURLRequest *theRequest;
24
25 @end
26
27 @implementation LQAsynDownload
28
29 @synthesize receiveData = _receiveData, fileName = _fileName,
30 theConnection=_theConnection, theRequest=_theRequest;
31
32 + (LQAsynDownload *) initWithURL:(NSURL *) url{
33 LQAsynDownload *asynDownload = [[LQAsynDownload alloc] init];
34 asynDownload.theRequest=[NSURLRequest requestWithURL:url
35 cachePolicy:NSURLRequestUseProtocolCachePolicy
36 timeoutInterval:60.0];
37 // create the connection with the request
38 // and start loading the data
39 return asynDownload;
40 }
41
42 - (void) startAsyn{
43 _contentLength=0;
44 _receiveLength=0;
45 self.receiveData = [[NSMutableData alloc] init];
46 self.theConnection = [[NSURLConnection alloc] initWithRequest:self.theRequest delegate:self];
47 }
48
49 //接收到http响应
50 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
51 _contentLength = [response expectedContentLength];
52 _fileName = [response suggestedFilename];
53 if (self.initProgress != nil) {
54 self.initProgress(_contentLength);
55 }
56 NSLog(@"data length is %lli", _contentLength);
57 }
58
59 //传输数据
60 -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
61 _receiveLength += data.length;
62 [_receiveData appendData:data];
63 if (self.loadedData != nil) {
64 self.loadedData(data.length);
65 }
66 NSLog(@"data recvive is %lli", _receiveLength);
67 }
68
69 //错误
70 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
71 [self releaseObjs];
72 NSLog(@"%@",error.description);
73 }
74
75 - (void) releaseObjs{
76 self.receiveData = nil;
77 self.fileName = nil;
78 self.theRequest = nil;
79 self.theConnection = nil;
80 }
81
82 //成功下载完毕
83 - (void) connectionDidFinishLoading:(NSURLConnection *)connection{
84 //数据写入doument
85 //获取完整目录名字
86 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
87 NSString *documentsDirectory = [paths objectAtIndex:0];
88 NSString *savePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory, _fileName];
89 //创建文件
90 [_receiveData writeToFile:savePath atomically:YES];
91 [self releaseObjs];
92 }
93
94
95 @end

调用代码:

1 LQAsynDownload *dwn = [LQAsynDownload initWithURL:[[NSURL alloc] initWithString:@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=fae75ab5d63f8794d3ff4f2ee6230ff4/faedab64034f78f09f9423fe7b310a55b3191c1b.jpg"]];
2
3 dwn.initProgress = ^(long long initValue){
4 _sum = initValue;
5 NSLog(@"%lli",initValue);
6 _rcv = 0;
7 dispatch_async(dispatch_get_main_queue(), ^{
8 self.pv.progress = 0.0;
9 self.pv.hidden = NO;
10 });
11 };
12
13 dwn.loadedData = ^(long long loadedLength){
14 dispatch_async(dispatch_get_main_queue(), ^{
15 if (_rcv == _sum) {
16 self.pv.hidden = YES;
17 } else {
18 _rcv += loadedLength;
19 self.pv.progress = _rcv/_sum;
20 }
21 });
22 };
23
24 [dwn startAsyn];

真相:

iOS异步下载下载进度条显示的更多相关文章
- python实现socket上传下载文件-进度条显示
在python的socket编程中,可以实现上传下载文件,并且在下载的时候,显示进度条,具体的流程如下图所示: 1. 服务器端代码如下: [root@python 519]# cat server.p ...
- iOS之UI--Quartz2D的入门应用--重绘下载圆形进度条
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- 使用 new XMLHttpRequest() 制作下载文件进度条
mui 进度控件使用方法: 检查当前容器(container控件)自身是否包含.mui-progressbar类: 当前容器包含.mui-progressbar类,则以当前容器为目标控件,直接显示进度 ...
- 赵雅智_android多线程下载带进度条
progressBar说明 在某些操作的进度中的可视指示器,为用户呈现操作的进度,还它有一个次要的进度条,用来显示中间进度,如在流媒体播放的缓冲区的进度. 一个进度条也可不确定其进度.在不确定模式下, ...
- iOS UIWebView 加载进度条的使用-WKWebView的使用,更新2017.6.26
1.由于项目中加载网络插件,直接使用了webview加载.使用了三方NJKWebViewProgress进度条的使用,近期在测试时发现,网络缓慢时出现白屏,有卡顿现象. 于是采用了WKWebView进 ...
- 【Android】读取sdcard卡上的全部图片而且显示,读取的过程有进度条显示
尽管以下的app还没有做到快图浏览.ES文件浏览器的水平,遇到大sdcard还是会存在读取过久.内存溢出等问题,可是基本思想是这种. 例如以下图.在sdcard卡上有4张图片, 打开app,则会吧sd ...
- Unity 异步加载 进度条
当我们进行游戏开发时,时常会进行场景切换,如果下个场景较大,切换时就会出现卡顿现象,甚至看起来像是"死机",非常影响用户体验,我们这时就可以运用异步加载,在界面上显示加载的进度条以 ...
- 【Winform】使用BackgroundWorker控制进度条显示进度
许多开发者看见一些软件有进度条显示进度,自己想弄,项目建好后发现并没有自己想象中的那么简单...看了网上很多教程后,写了一个小Demo供网友们参考~~,Demo的网址:http://pan.baidu ...
- Extjs 使用fileupload插件上传文件 带进度条显示
一.首先我们看看官方给出的插件的解释: 一个文件上传表单项具有自定义的样式,并且可以控制按钮的文本和 像文本表单的空文本类似的其他特性. 它使用一个隐藏的文件输入元素,并在用户选择文件后 在form提 ...
- Ajax上传文件进度条显示
要实现进度条的显示,就要知道两个参数,上传的大小和总文件的大小 html5提供了一个上传过程事件,在上传过程中不断触发,然后用已上传的大 小/总大小,计算上传的百分比,然后用这个百分比控制div框的显 ...
随机推荐
- js对象定义
JS中的对象定义方式,跟服务端,还是有很大差别的! 现在来说一下JS类的定义 工厂模式 function creatHeven(name,age){ var temp =new Object(); t ...
- css3动画中的steps值详解
css3的动画的animation-timing-function属性定义了动画的速度曲线,一般的速度曲线大家都知道,什么ease,linear,ease-in,ease-out,还有自定义贝塞尔曲线 ...
- 关于codeMirror插件使用的一个坑
codeMirror插件可以做语法高亮渲染,但它操作过程是这样的:先从 textarea中读取值放到codemirror动态生成的div中,根据textarea中的换行个数确定行数,根据正则表达来高亮 ...
- PAT 1013. 数素数 (20)
令Pi表示第i个素数.现任给两个正整数M <= N <= 104,请输出PM到PN的所有素数. 输入格式: 输入在一行中给出M和N,其间以空格分隔. 输出格式: 输出从PM到PN的所有素数 ...
- HRV基础
Source: Mostly from wiki. Heart rate variability (HRV,心率变异性) is the physiological phenomenon of vari ...
- linux的一些常用命令
这几天正好在研究linux系统,打算将下一个项目部署在linux系统的服务器上已提高安全性(被window 2003已经折磨的不行了),经过各方了解和深思熟虑后决定使用linux系统的CentOs版本 ...
- C# 7.0 新特性3: 模式匹配
本文参考Roslyn项目Issue:#206,及Docs:#patterns. 1. C# 7.0 新特性1: 基于Tuple的“多”返回值方法 2. C# 7.0 新特性2: 本地方法 3. C# ...
- des解密不完整,前面几位是乱码的解决办法
在工作中遇到的Des解密问题,第三方发来的数据需要我们进行des解密,但是解密的结果前几位始终是乱码.废了半天劲,终于找到了问题所在. 下面先介绍一下des,了解des的同学可以直接看下面的解决办法. ...
- 开源免费的HTML5游戏引擎——青瓷引擎(QICI Engine) 1.0正式版发布了!
青瓷引擎的成长 青瓷引擎自2015年4月项目启动开始,7月首次亮相2015年ChinaJoy,便得到业界的极大关注,随后开启限量测试,收到数百个开发者团队的试用申请及反馈,期间经历了18个内测版本,完 ...
- closure!
总结一下闭包. 闭包的定义:当一个内部函数被其外部函数之外的变量所引用时,就形成了一个闭包. 一个最简单的闭包: function A(){ var count=0; return function( ...