【罗国强原创】

今天被刺激了,愤概地要写下这边博文。

说到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=;
_receiveLength=;
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:];
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

 //
// LQAsynDownload.h
// lgTest
//
// Created by yons on 14-2-14.
// Copyright (c) 2014年 GQ. All rights reserved.
// #import <Foundation/Foundation.h> 11 typedef void (^initProgress)(long long initValue);
12
13 typedef void (^loadedData)(long long loadedLength); @interface LQAsynDownload : NSObject<NSURLConnectionDataDelegate> @property (strong) NSURL *httpURL; 19 @property (copy) void (^initProgress)(long long initValue);
20
21 @property (copy) void (^loadedData)(long long loadedLength); + (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=;
_receiveLength=;
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];
53 if (self.initProgress != nil) {
54 self.initProgress(_contentLength);
55 }
NSLog(@"data length is %lli", _contentLength);
} //传输数据
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
_receiveLength += data.length;
[_receiveData appendData:data];
63 if (self.loadedData != nil) {
64 self.loadedData(data.length);
65 }
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:];
NSString *savePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory, _fileName];
//创建文件
[_receiveData writeToFile:savePath atomically:YES];
[self releaseObjs];
} @end

调用代码:

 LQAsynDownload *dwn = [LQAsynDownload initWithURL:[[NSURL alloc] initWithString:@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=fae75ab5d63f8794d3ff4f2ee6230ff4/faedab64034f78f09f9423fe7b310a55b3191c1b.jpg"]];

     dwn.initProgress = ^(long long initValue){
_sum = initValue;
NSLog(@"%lli",initValue);
_rcv = ;
dispatch_async(dispatch_get_main_queue(), ^{
self.pv.progress = 0.0;
self.pv.hidden = NO;
});
}; dwn.loadedData = ^(long long loadedLength){
dispatch_async(dispatch_get_main_queue(), ^{
if (_rcv == _sum) {
self.pv.hidden = YES;
} else {
_rcv += loadedLength;
self.pv.progress = _rcv/_sum;
}
});
}; [dwn startAsyn];

真相:

情人节第二个礼物:

以前觉得很神奇的野,用心去试试,会觉得很简单,不是吗?

ios专题 - 异步下载加下载进度显示的更多相关文章

  1. iOS Cell异步图片加载优化,缓存机制详解

    最近研究了一下UITbleView中异步加载网络图片的问题,iOS应用经常会看到这种界面.一个tableView上显示一些标题.详情等内容,在加上一张图片.这里说一下这种思路. 为了防止图片多次下载, ...

  2. NGUI的异步场景加载进度条

    1.直接创建三个场景,其中第二个场景是用来显示进度条加载的界面,进度条用UISlider,不会的看我前面的博文就可以了. 2.这里提供两种方法,建议使用第一种,加载比较平缓 方法一: using Sy ...

  3. iOS 自定义任意形状加载进度条(水波纹进度条)

    1. 项目中要做类似下面的加载动画: 先给出安卓的实现方式 2.iOS的实现方式参考了下面两位的,感谢. 以任意底部图片为背景的加载动画 和 水波纹动画 最后附上自己的demo

  4. iOS WKWebView添加网页加载进度条(转)

    一.效果展示 WKWebProgressViewDemo.gif 二.主要步骤 1.添加UIProgressView属性 @property (nonatomic, strong) WKWebView ...

  5. BackgroundWorker实现的winfrom中实现异步等待加载图片显示

    BackgroundWorker简介    BackgroundWorker在winfrom中有对应控件,该有三个事件:DoWork .ProgressChanged 和 RunWorkerCompl ...

  6. WPF 客户端浏览器 添加Loading加载进度

    在windows开发界面时,使用浏览器来请求和显示网页内容,是比较常见的. 但是在请求网页内容时,因网速或者前端功能复杂加载较慢,亦或者加载时遇到各种问题,如空白/黑屏/加载不完整/证书问题等. 因此 ...

  7. 灵活、可高度自定义的——Progress进度圈、弹窗、加载进度、小菊花

    DDProgressHUD的介绍 提供了四种类型的展示: 显示无限旋转的加载图(比如小菊花,可以自定义),显示文字信息.网络刷新时经常用到. 显示加载进度的动画,也可以显示文字.网络下载时用的比较多, ...

  8. 《C/C++实现Console下的加载进度条模拟[美观版]》

    前言   有时候我们会遇到在CMD或DOS控制台上出现的加载进度条,虽然不是如网页和软件写的美观.但确确实实也有着自己的特色.而且,一个好看的加载进度条也能增加用户使用控制台程序的体验!所以,拿来研究 ...

  9. IOS GCD图片数据异步下载,下载完成后合成显示

    关于GCD使用详解,请看我的上一篇blog:http://www.cnblogs.com/xin-lang/p/6278606.html 前段时间遇到个需要异步下载,下载完成后再组合显示的东西.这里我 ...

随机推荐

  1. Java笔记(七)……函数

    函数的定义 定义在类中具有特定功能的一段独立小程序,也称方法. 函数的格式 1: 修饰符 返回值类型 函数名(参数类型 形式参数1,参数类型 形式参数2,) 2: { 3: 执行语句; 4: retu ...

  2. Installing your app on your Windows RT device

    Alright… so my app is almost finished and I want to install it for real on my Surface tablet. How do ...

  3. url 编码方法

    这个方法用于把 字符串转换成url 的编码 第一个参数是 字符串,第二个参数是 指定的编码(UTF-8 ,GBK, gbk2312...) private string UrlEncode(strin ...

  4. Maintainable JavaScript(编写可维护的JavaScript) PART I Style Guidelines

    “Programs are meant to be read by humans and only incidentally( 顺便:偶然地:附带地) for computers to execute ...

  5. .Net设计模式_开篇

    前言 其实以前看过两次设计模式,现在想来,几乎已经对设计模式没有任何印象,说明根本没有理解.或者说几乎不用,所以我除了单列.工厂外的设计模式几乎全部忘记了.最近需要写一个引擎,想用UML设计整体的架构 ...

  6. HDU4619+匈牙利

    /* 匈牙利算法 二分匹配 最小点覆盖=最大匹配. 即踢掉最小点覆盖 */ #include<stdio.h> #include<string.h> #include<s ...

  7. SQL Server将一列的多行内容拼接成一行的问题讨论

    转自http://blog.csdn.net/rolamao/article/details/7745972 昨天遇到一个SQL Server的问题:需要写一个储存过程来处理几个表中的数据,最后问题出 ...

  8. C#如何检测一个字符串是不是合法的URL

    C#如何检测一个字符串是不是合法的URL using System.Text.RegularExpressions;    /// <summary>         /// 检测串值是否 ...

  9. 步步为营Hibernate全攻略(一)构建Hibernate框架环境

    任何一项新技术的出现都有它的必然性,Hibernate也不例外,所以在掌握Hibernate的具体应用之前我们一定先要了解Hibernate是什么?使用Hibernate会给我们的程序开发带来哪些好处 ...

  10. [GIF] GIF Loop Coder - Introduction

    Introducing the program, GIF Loop Coder, which allows you to make looping animated gifs (and other t ...