【iOS】AFNetworking断点下载

AFNetworking也使用了好长一段时间了,一直都是使用它做一些简单的网路请求,比如GET请求和POST请求。但是真正的数据的下载和上传都没使用过。今天就暂时先写下一个数据的断点下载的Demo,后续有条件在补充一个断点续传的例子。

关于AFNetworking的断点下载的操作难度不大,知道调用什么方法什么类就就好了。也许这就是苹果一个把iOS开发做的流程化和简单化的原因吧,虽说AFNetworking是第三方的但也很好的证明了苹果的这一点。废话不多说,直接上效果图了。


从上到下一次说明:

第一行的Lable,显示当前的下载网速。实际是1秒测一次,当前的下载Byte数减去上1秒的下载Byts数 就是等于速度了。做一这个速度严格的说不是当前的速度。

第二行的Lable,显示下载进度,以百分比的形式显示。

第三行的进度条。

第四行的Lable 显示已经下载了多少MB和整个文件的MB。

第五行的按钮,用于检测网速。

第六行的按钮,点击开始下载。

第七行的按钮,暂停和继续下载。

下载之前我们需要找一个下载链接,这个是我找的一个:

http://ftp-idc.pconline.com.cn/ceb7f6f871c6ec356127881b13eb8e3e/pub/download/201010/WPS2015.exe

下一步就是写代码了。

首先需要AFNetworking库,怎么包含这个库,此文略,请自行百度。

<pre name="code" class="objc">#import "ViewController.h"
#import "AFNetworking.h"
//http://ftp-idc.pconline.com.cn/ceb7f6f871c6ec356127881b13eb8e3e/pub/download/201010/WPS2015.exe
@interface ViewController (){
	AFHTTPRequestOperationManager *_manage;
	AFHTTPRequestOperation *_downloadOperation;
	NSURL *_url;
	NSTimer *_timer;
	CGFloat _currentByte;
	CGFloat _totalByte;
	CGFloat _lastByte;
	CGFloat _nowByte;
	BOOL _flag;
}
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet UILabel *speedLabel;
@property (weak, nonatomic) IBOutlet UILabel *proLabel;

@property (weak, nonatomic) IBOutlet UILabel *downLabel;
@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	_flag = NO;
	_url = [NSURL URLWithString:@"http://ftp-idc.pconline.com.cn/ceb7f6f871c6ec356127881b13eb8e3e/pub/download/201010/WPS2015.exe"];
	self.progressView.progress = 0;
	// Do any additional setup after loading the view, typically from a nib.
}
/**
 *  网络监测按钮
 *
 *  @param sender sender description
 */
- (IBAction)testNetwork:(id)sender {
	_manage = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:_url];
	[_manage.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
		if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
			UIAlertView * netStatusAl = [[UIAlertView alloc] initWithTitle:@"服务器连接失败" message:@"请检查网络连接" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
			[netStatusAl show];  //请检查网络连接
		}
	}];
	//开始监听
	[_manage.reachabilityManager startMonitoring];
}
/**
 *  开始下载按钮点击事件
 *
 *  @param sender sender description
 */
- (IBAction)startDownload:(id)sender {
	//制作一个请求头
	NSURLRequest *request = [NSURLRequest requestWithURL:_url];
	_downloadOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
	//设置一个下载路径
	NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString *downloadPath = [cacheDirectory stringByAppendingPathComponent:@"word2007.exe"];
	NSLog(@"downloadPath = %@",downloadPath);//打印文件下载路劲
	_downloadOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:YES];
	__weak ViewController *wself = self;
	//下载进度
	[_downloadOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
		_totalByte = totalBytesExpectedToRead; //全部字节
		_currentByte = totalBytesRead;  //已经下载的字节
		wself.downLabel.text = [NSString stringWithFormat:@"%.2fMB/%.2fMB",_currentByte/1024/1024,_totalByte/1024/1024];
		//这里会不断调用,保证定时器只是一个 就只需要执行一次
		static dispatch_once_t onceToken;
		dispatch_once(&onceToken, ^{
			//减少定时间隔 可以是测量的网速 更加接近当前网速
			_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(currentSpeed) userInfo:nil repeats:YES];
		});
		//下载进度
		float progress = (float)totalBytesRead/totalBytesExpectedToRead;
		wself.progressView.progress = progress;
		wself.proLabel.text = [NSString stringWithFormat:@"下载进度:%f%%",progress*100];
	}];
	[_downloadOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
		; //下载完成
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		; //下载出错
	}];
	//开始下载
	[_downloadOperation start];
}
/**
 *  暂停开始按钮
 *
 *  @param sender sender description
 */
- (IBAction)stop_start:(id)sender {
	UIButton *button = (UIButton *)sender;
	//开始
	if (_downloadOperation.isPaused) {
		[_downloadOperation resume];
		//恢复定时器
		_timer.fireDate = [NSDate distantPast];
		[button setTitle:@"暂停" forState:UIControlStateNormal];
	}
	//暂停
	else{
		[_downloadOperation pause];
		//暂停定时器
		_timer.fireDate = [NSDate distantFuture];
		[button setTitle:@"继续" forState:UIControlStateNormal];
	}
}
/**
 *  定时器1秒定时事件 
 *  监测网速
 */
- (void)currentSpeed{
	_flag = !_flag;
	if (_flag == YES) {//获取上一秒下载的Byte数
		_lastByte = _currentByte;
	}
	if (_flag == NO) { //获取当前的下载的Byte数
		_nowByte = _currentByte;
		_speedLabel.text = [NSString stringWithFormat:@"当前网速:%.2fkB/s",(_nowByte - _lastByte)/1000];
	}
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

@end


 代码部分就是这样的的,UI部分就是上面的截图样式,直接拖的控件。代码下载---- 
 请点击我

我们进入下载文件的路径可以占到刚才下载的文件了。那个.exe文件就是了。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值