NSWebView NSURLSession 简化NSURLSession

//NSWebView

#import "ViewController.h"

@interface ViewController (){
    UISearchBar *_searchBar;
    UIWebView *_webView;
    UIToolbar *_toolBar;//底部工具栏
    UIBarButtonItem *_backButton;//回退
    UIBarButtonItem *_forwardButton;//前进
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layout];
}
-(void)layout{
    //添加搜索栏
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, 375, 44)];
    _searchBar.delegate = self;
    [self.view addSubview:_searchBar];
    //添加浏览器
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, 375, 559)];
    _webView.backgroundColor = [UIColor purpleColor];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    //添加工具栏
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 623, 375, 44)];
    //设置工具栏按钮(回退和前进)
    _backButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"left"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    
    UIBarButtonItem *btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    _forwardButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"right"] style:UIBarButtonItemStyleDone target:self action:@selector(forward)];
    _toolBar.items = @[_backButton,btnSpace,_forwardButton];
    [self.view addSubview:_toolBar];
}
-(void)back{
    [_webView goBack];
}
-(void)forward{
    [_webView goForward];
}
-(void)request:(NSString *)urlStr{
    NSURL *url = [[NSURL alloc]init];
    //创建url
    if([urlStr hasPrefix:@"file://"]){
        //1.获取文件名位置
        NSRange range = [urlStr rangeOfString:@"file://"];
        NSString *fileName = [urlStr substringFromIndex:range.length];
        NSLog(@"%@",fileName);
    
    //2.获取文件位置
    url = [[NSBundle mainBundle]URLForResource:fileName withExtension:nil];
    }
    else if([urlStr hasPrefix:@"http://"]){
        url = [NSURL URLWithString:urlStr];
    }
    else{//如果和符合任何协议则进行百度搜索
        urlStr = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",urlStr];
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        url = [NSURL URLWithString:urlStr];
    }
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //加载请求页面
    [_webView loadRequest:request];
    
//    urlStr = _searchBar.text;
//    url = [NSURL URLWithString:urlStr];
//    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}
#pragma mark searchBar代理方法
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self request:searchBar.text];
    NSLog(@"搜索!!!%@",searchBar.text);
}
#pragma mark webView代理方法
#pragma mark 开始加载
-(void)webViewDidStartLoad:(UIWebView *)webView{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
#pragma mark 加载完毕
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //显示当前加载的url
    NSLog(@"%@",webView.request.URL);
    _searchBar.text  = [NSString stringWithFormat:@"%@",webView.request.URL];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}



//NSURLSession

#import "ViewController.h"

@interface ViewController (){
    UIButton *buttonDown;
    UIButton *buttonCancel;
    UIButton *buttonG;
    UIButton *buttonRe;
    UITextField *text;
    UIProgressView *progressView;
    UILabel *label;
    NSMutableData *_data;
    long long totalLength;
    NSURLSessionDownloadTask *_downloadTask;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layout];
    }
-(void)layout{
    self.view.backgroundColor = [UIColor colorWithRed:0.8 green:0.6 blue:0.5 alpha:1];
    
    text = [[UITextField alloc]initWithFrame: CGRectMake(20, 40, 335, 25)];
    text.borderStyle = UITextBorderStyleRoundedRect;
    text.text = @"http://b.zol-img.com.cn/desk/bizhi/image/7/2560x1600/1447404575613.jpg";
    text.placeholder = @"请输入要下载的地址";
    [self.view addSubview:text];
    
    
    progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(20, 90, 335, 25)];
    [self.view addSubview:progressView];
    
    
    label = [[UILabel alloc]initWithFrame:CGRectMake(20, 140, 100, 25)];
    label.text = @"Hello";
    label.font = [UIFont fontWithName:@"Arial" size:20];
    [self.view addSubview:label];
    
    
    buttonDown = [[UIButton alloc]initWithFrame:CGRectMake(20, 500, 40, 25)];
    [buttonDown setTitle:@"下载" forState:UIControlStateNormal];
    buttonDown.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1];
    [buttonDown addTarget:self action:@selector(Download) forControlEvents:UIControlEventTouchUpInside];
     [buttonDown setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.view addSubview:buttonDown];
    
    
    
    buttonCancel =[[UIButton alloc]initWithFrame:CGRectMake(120, 500, 40, 25)];
    [buttonCancel setTitle:@"取消" forState:UIControlStateNormal];
    buttonCancel.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1];
     [buttonCancel setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [buttonCancel addTarget:self action:@selector(Cancel) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonCancel];
    
    
    buttonG = [[UIButton alloc]initWithFrame:CGRectMake(220, 500, 40, 25)];
    [buttonG setTitle:@"挂起" forState:UIControlStateNormal];
    buttonG.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1];
    [buttonG setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [buttonG addTarget:self action:@selector(Suspend) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonG];
    
    buttonRe = [[UIButton alloc]initWithFrame:CGRectMake(320, 500, 40, 25)];
    [buttonRe setTitle:@"恢复" forState:UIControlStateNormal];
    buttonRe.backgroundColor = [UIColor colorWithRed:0.8 green:0.9 blue:0.8 alpha:1];
     [buttonRe setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [buttonRe addTarget:self action:@selector(Resume) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonRe];
}

-(void)Download{
    NSString *urlStr =text.text;

    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f];
    //3.创建session会话
    //配置session
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForRequest = 10.0f;//请求超时时间
    sessionConfig.allowsCellularAccess = YES;//是否允许蜂窝网络下载(2G/3G/4G)
    //创建会话
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理
    _downloadTask = [session downloadTaskWithRequest:request];
    [_downloadTask resume];
    
}


#pragma mark 下载取消
-(void)Cancel{
    NSLog(@"Cancel");
    [_downloadTask cancel];
}

#pragma mark 下载暂停
-(void)Suspend{
    NSLog(@"暂停");
    [_downloadTask suspend];
}

#pragma mark 下载恢复
-(void)Resume{
    NSLog(@"Resume");
    [_downloadTask resume];
}
//设置进度条状态
-(void)setProgressStatus:(int64_t)totalBytesWritten expectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //异步处理进程(获取主队列)
    dispatch_async(dispatch_get_main_queue(), ^{progressView.progress = (float) totalBytesWritten/totalBytesExpectedToWrite;
        if (totalBytesWritten == totalBytesExpectedToWrite){
            label.text = @"下载完成";
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }
        else{
            label.text = @"正在下载...";
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        }
    });
}


#pragma mark 下载任务代理
#pragma mark 下载中(会多次调用,可以记录下载进度)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    NSLog(@"1.%lld 2.%lld 3.%lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    
    [self setProgressStatus:totalBytesWritten expectedToWrite:totalBytesExpectedToWrite];

}

#pragma mark 下载完成(更改保存路径)
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSLog(@"%@",location);
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:@"图片3.jpg"];
    NSLog(@"%@",path);
    
    NSURL *saveUrl = [NSURL fileURLWithPath:path];
    NSLog(@"%@",saveUrl);
    //关键:复制文件,从location->saveUrl
    NSError *error;
    [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&error];
    if(error){
        NSLog(@"%@",error.localizedDescription);
    }
}

#pragma mark 任务完成时调用,不管是否完成功
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
//如果存在错误,打印一下
    if(error){
        NSLog(@"Error is :%@",error.localizedDescription);
    }
}



//简化NSURLSession


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self downloadFile];
}
-(void)downloadFile{
    //1.创建url
    NSString *urlStr = @"http://i-7.vcimg.com/trim/867a1fe997bf3baeebbd223ae9aecdc8142598/trim.jpg";
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3.创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    
    //4.创建下载任务
    NSURLSessionDownloadTask *downloadTask =[session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        if(!error){
        NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        path = [path stringByAppendingPathComponent:@"图片.jpg"];
            NSLog(@"%@",path);
            NSError *saveError;
            NSURL *saveUrl = [NSURL fileURLWithPath:path];
            [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&saveError];
            if (!saveError) {
                NSLog(@"保存成功!");
            }
            else {
                NSLog(@"保存文件出错,Error is :%@",saveError.localizedDescription);
            }
        }
        else{
        
            NSLog(@"下载出错:%@",error.localizedDescription);
        }
        }];
    [downloadTask resume];
}

你可能感兴趣的:(NSWebView NSURLSession 简化NSURLSession)