#import "ViewController.h"
#import "ProgressButton.h"
#import "DownloadOperation.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet ProgressButton *progressBtn;
@property (nonatomic, strong) DownloadOperation *download;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)pause:(id)sender {
[self.download pause];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSString *URLStr =@"http://localhost/01UI基础复习.mp4";
URLStr = [URLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:URLStr];
self.download = [DownloadOperation downloadWithUrl:url progress:^(CGFloat progress) {
dispatch_async(dispatch_get_main_queue(), ^{
self.progressBtn.progress = progress;
});
} finish:^(NSString *targetPath, NSError *error) {
NSLog(@"下载完成%@ -- %@",targetPath,[NSThread currentThread]);
}];
}
@end
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface DownloadOperation : NSObject
+ (instancetype)downloadWithUrl:(NSURL *)url progress:(void(^)(CGFloat progress))progress finish:(void(^)(NSString *targetPath,NSError *error))finish;
- (void)pause;
@end
#import "DownloadOperation.h"
@interface DownloadOperation ()<NSURLConnectionDataDelegate>
@property (nonatomic, copy) void (^progress)(CGFloat);
@property (nonatomic, copy) void (^finish)(NSString *, NSError *);
@property (nonatomic, assign) long long fileSize;
@property (nonatomic, assign) long long currentLocalSize;
@property (nonatomic, assign) long long currentSize;
@property (nonatomic, strong) NSOutputStream *output;
@property (nonatomic, strong) NSURLConnection *connection;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, strong) NSURL *url;
@end
@implementation DownloadOperation
+ (instancetype)downloadWithUrl:(NSURL *)url progress:(void (^)(CGFloat))progress finish:(void (^)(NSString *, NSError *))finish {
DownloadOperation *download = [[self alloc]init];
download.progress = progress;
download.finish = finish;
download.url = url;
[download startDownload];
return download;
}
- (void)pause {
[self.connection cancel];
}
- (void)startDownload {
NSURL *url = self.url;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
self.filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
self.fileSize = response.expectedContentLength;
self.currentLocalSize = [self checkLocalFile];
self.currentSize = self.currentLocalSize;
if (self.currentLocalSize == self.fileSize) {
if (self.progress) {
self.progress(1);
}
if (self.finish) {
self.finish(self.filePath,nil);
}
return;
}
[self download:url];
}
- (long long)checkLocalFile {
long long fileSize = 0;
NSFileManager *manager = [NSFileManager defaultManager];
NSDictionary *att = [manager attributesOfItemAtPath:self.filePath error:NULL];
long long localFileSize = att.fileSize;
if (localFileSize > self.fileSize) {
[manager removeItemAtPath:self.filePath error:NULL];
fileSize = 0;
}else if (localFileSize == self.fileSize) {
fileSize = localFileSize;
}else {
fileSize = localFileSize;
}
return fileSize;
}
- (void)download:(NSURL *)url {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLocalSize];
[request setValue:range forHTTPHeaderField:@"Range"];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
[[NSRunLoop currentRunLoop] run];
});
}
#pragma mark - NSURLConnection 代理
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"接收到响应%@ -- %lld",response,response.expectedContentLength);
self.output = [[NSOutputStream alloc]initToFileAtPath:self.filePath append:YES];
[self.output open];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
self.currentSize += data.length;
CGFloat progress = (CGFloat)self.currentSize / self.fileSize;
if (self.progress) {
self.progress(progress);
}
[self.output write:data.bytes maxLength:data.length];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"下载完成了");
dispatch_async(dispatch_get_main_queue(), ^{
if (self.finish) {
self.finish(self.filePath,nil);
}
});
[self.output close];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"出错了");
dispatch_async(dispatch_get_main_queue(), ^{
if (self.finish) {
self.finish(nil,error);
}
});
}
@end