【iOS】NSURLSession断点下载

关于NSURLSession可以阅读这两篇文章:

iOS中利用NSURLSession进行文件断点下载

者两篇里面也都有实例。

在我的上一篇【iOS】 AFNetworking断点下载介绍的使用AFNetworking进行断点下载。现在做了一个关于NSURLSession的断点下载,个人感觉使用AFNetworking操作简单一下。但是使用AFNetworking意味着工程的代码量会增大许多。关于第三方库的使用与否,个人觉得我们在是实际项目中需要根据实际情况来选择,不是一味地追求简单。比如下载一个简单的JSON数据,我们使用系统的NSURLConnection就足够了,如果在使用AFNetworking就有点累赘了。所以我们需要多方面权衡一下做出选择。

上了上面两位博主的博客我们对NSURLSession是什么怎么使用有了比较全面的了解了,着了我的代码是在上面两位的整合。

首先说明一点的是,在下载完成后显示图片那里,由于文件路径比较深,在下载完成后并不能马上显示出来。但是我们可以把文件路径修改把文件放在桌面,这样就可马上显示出来。

效果图:


#import "ViewController.h"
#define URLPATH  @"http://img6.faloo.com/Picture/0x0/0/747/747488.jpg"

//#define URLPATH  @"http://ftp-idc.pconline.com.cn/ceb7f6f871c6ec356127881b13eb8e3e/pub/download/201010/WPS2015.exe"

//http://ftp-idc.pconline.com.cn/ceb7f6f871c6ec356127881b13eb8e3e/pub/download/201010/WPS2015.exe
@interface ViewController ()<NSURLSessionDownloadDelegate>
{
	NSURLSessionDownloadTask *_task; //下载任务
	NSData *_resumeData;             //下载的数据
	NSURLSession *_session;          //session
	NSURL *_url;                     //下载链接
	NSData *_downloadData;           //暂存下载的数据
	CGFloat _totalBytes;             //数据的总得byte
	CGFloat _currentBytes;           //当前下载了的byte
}

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	
	[self systemInit];
	// Do any additional setup after loading the view, typically from a nib.
}
/**
 *  初始化相关对象
 */
- (void)systemInit{
	//设置进度条初始值
	self.progressView.progress = 0;
	_url = [NSURL URLWithString:URLPATH];
	NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
	_session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
}
/**
 *  开始下载按钮
 *
 *  @param sender sender description
 */
- (IBAction)startButton:(id)sender {
	NSLog(@"开始下载");
	_task = [_session downloadTaskWithURL:_url];
	[_task resume];
}
/**
 *  暂停下载按钮
 *
 *  @param sender sender description
 */
- (IBAction)pauseButton:(id)sender {
	NSLog(@"暂停下载");
	[_task cancelByProducingResumeData:^(NSData *resumeData) {
		_downloadData = resumeData;
		_task = nil;
	}];
}
/**
 *  继续下载
 *
 *  @param sender sender description
 */
- (IBAction)resumeButton:(id)sender {
	NSLog(@"继续下载");
	if (!_task) {
		if (_downloadData) {
			_task = [_session downloadTaskWithResumeData:_downloadData];
		}
		else{
			_task = [_session downloadTaskWithURL:_url];
		}
	}
	[_task resume];
}
#pragma mark - 实现NSURLSessionDownloadDelegate协议方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
	NSLog(@"下载完成");
	NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];//把这个路径修改 为桌面 图片显示就会很快
	NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
	NSFileManager *fileManage = [NSFileManager defaultManager];
	BOOL success = [fileManage moveItemAtPath:location.path toPath:filePath error:nil];
	self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:filePath]];
	if (success) {
		dispatch_async(dispatch_get_main_queue(), ^{
			self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:filePath]];
		});
	}
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
	  didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
	NSLog(@"下载中。。。");
	_currentBytes = totalBytesWritten;
	_totalBytes = totalBytesExpectedToWrite;
	CGFloat progress = totalBytesWritten/totalBytesExpectedToWrite;
	NSString *currentText = [NSString stringWithFormat:@"%.2fMB/%.2fMB",_currentBytes/1024/1024,_totalBytes/1024/1024];
	NSString *proText = [NSString stringWithFormat:@"%.2f%%",((float)totalBytesWritten/totalBytesExpectedToWrite)*100];
	dispatch_async(dispatch_get_main_queue(), ^{
		self.progressView.progress = progress;
		self.progressLabel.text = proText;
		self.currentLabel.text = currentText;
	});
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
	
}

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

@end
最后贴上代码的下载  --- 请点击我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值