iOS 自定义网页内容下载器

自定义iOS下载器

用途:打开一个需要下载文件的网页后,下载该文件,保存到本地

调用MBProgressHUD展示下载进度


话不多说,上效果图










代码:

//声明文件:

//
//  JakDownloadlWebViewController.h
//
//  Created by zyh on 16/6/29.
//  Copyright © 2016年 HC. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface JakDownloadlWebViewController : UIViewController

@property(nonatomic,strong)UIWebView *webView;


@end

//实现文件

//
//  JakDownloadlWebViewController.m
//
//  Created by zyh on 16/6/29.
//  Copyright © 2016年 HC. All rights reserved.
//

#import "JakDownloadlWebViewController.h"
#import "MBProgressHUD.h"

@interface JakDownloadlWebViewController()<UIWebViewDelegate,NSURLSessionDelegate>
@property(nonatomic,strong)MBProgressHUD *downloadHUD;
@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;

@end


@implementation JakDownloadlWebViewController

-(void)viewDidLoad{
    [super viewDidLoad];

    //创建网页视图并开启下载
    self.webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.delegate = self;
    NSURLRequest *request= [NSURLRequest requestWithURL:[NSURL URLWithString:@"xxxx"]];
    [self showHUDWithRequest:request];
}

//离开页面时清除缓存
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}


//开启下载,并弹出HUD,显示下载进度,取消按钮
-(void)showHUDWithRequest:(NSURLRequest *)request{
    
    //配置HUD,添加取消下载按钮
    self.downloadHUD = [MBProgressHUD showHUDAddedTo:self.webView animated:YES];
    self.downloadHUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
    self.downloadHUD.label.text = @"正在下载";
    [self.downloadHUD.button setTitle:@"取消下载" forState:UIControlStateNormal];
    [self.downloadHUD.button addTarget:self action:@selector(cancelDownload) forControlEvents:UIControlEventTouchUpInside];
    self.downloadHUD.minSize = CGSizeMake(150.f, 150.f);
    
    //开启下载任务
    NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:nil];
    self.downloadTask = [session downloadTaskWithRequest:request];
    [self.downloadTask resume];
    
}

//在下载过程中取消下载
-(void)cancelDownload{
    [self.downloadTask cancel];
    self.downloadTask = nil;
}


#pragma  mark --UIWebViewDelegate
//调用代理方法,打印网页JS代码
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"javaScript:--------->{%@}",[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"]);
}

//网页加载失败时调用,弹窗提示失败原因
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    NSDictionary *userInfo = error.userInfo;
    NSString *reason = userInfo[@"NSLocalizedDescription"];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"连接失败!" message:reason preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark -- NSURLSessionDownloadDelegate
//完成下载保存文件到本地
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]stringByAppendingPathComponent:@"download"];
    
    // 创建目录
    [fileManager createDirectoryAtPath:documentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
    NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[downloadTask.response URL] lastPathComponent]];
    
    //若下载文件本身已存在,就将之替换掉
    if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
            [fileManager removeItemAtURL:fileURL error:NULL];
    }
        [fileManager moveItemAtURL:location toURL:fileURL error:NULL];
    
    
}


//下载过程中,获取下载进度,并在主线程中刷新展示
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    float progress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
    NSString *downloadProgress = [NSString stringWithFormat:@"%.2f%%",progress*100];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.downloadHUD.progress = progress;
        self.downloadHUD.detailsLabel.text =downloadProgress;
    });

}


#pragma mark -- NSURLSessionTaskDelegate
//下载任务完成:(中途取消下载也视为任务完成)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

    //展示不同的图片
    NSString *title = @"下载完成";
    NSString *imageName = @"Checkmark";
    if (error!=nil) {
        NSLog(@"下载失败:%@", error);
        NSDictionary *userInfo = error.userInfo;
        title = userInfo[@"NSLocalizedDescription"];
        imageName = @"cancelDownload";
        }
    
 
    //展示下载结果
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        self.downloadHUD.customView = imageView;
        self.downloadHUD.mode = MBProgressHUDModeCustomView;
        self.downloadHUD.label.text = title;
        self.downloadHUD.detailsLabel.hidden = YES;
        self.downloadHUD.button.hidden = YES;
        [self.downloadHUD hideAnimated:YES afterDelay:1.0f];
    });

}
@end


目前对于NSURLSessionDownloadDelegate以及NSURLSessionTaskDelegate里的各种代理方法正在探索研究中,欢迎有对这两个下载以及线程代理理解较深的大神指点.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值