NSWebView NSURLSession 簡化NSURLSession

//NSWebView
web

#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);
    }
}

session



//簡化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]; }
相關文章
相關標籤/搜索