Objective-c 网络编程3 NSURLSession

//
//  ViewController.m
//  网络编程3
//
//  Created by DC017 on 15/12/10.
//  Copyright © 2015年 DC017. All rights reserved.
//
#pragma mark NSURLSession 学习

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>
{
    UITextField * textfield;
    UIButton * xiazai;
    UIButton * quxiao;
    UIButton * zanting;
    UIButton * huifu;
    UILabel * label;

    UIProgressView * progress;
    
    NSURLSessionDownloadTask *downloadTask;
    
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layout];
    // Do any additional setup after loading the view, typically from a nib.
}
//layout布局
-(void)layout{
    textfield=[[UITextField alloc]initWithFrame:CGRectMake(20, 60, 300, 20)];
    textfield.layer.borderWidth=1;
    textfield.layer.borderColor=[UIColor redColor].CGColor;
    textfield.text=@"http://b.zol-img.com.cn/desk/bizhi/image/5/2560x1600/1414029841427.jpg";
    //设置圆角
    textfield.layer.cornerRadius=4;
    [self.view addSubview:textfield];
    
    
    label=[[UILabel alloc]initWithFrame:CGRectMake(60, 200, 80, 20)];
    label.textColor=[UIColor redColor];
    [self.view addSubview:label];
    
    progress =[[UIProgressView alloc]initWithFrame:CGRectMake(20, 100,300 ,5)];
    
    [self.view addSubview:progress];
    
    xiazai=[[UIButton alloc]initWithFrame:CGRectMake(20, 400, 60, 20)];
    zanting=[[UIButton alloc]initWithFrame:CGRectMake(100, 400, 60, 20)];
    huifu=[[UIButton alloc]initWithFrame:CGRectMake(180, 400, 60, 20)];
    quxiao=[[UIButton alloc]initWithFrame:CGRectMake(260, 400, 60, 20)];
    
    
    [xiazai  setTitle:@"下载" forState:UIControlStateNormal];
    [zanting setTitle:@"暂停" forState:UIControlStateNormal];
    [huifu setTitle:@"恢复" forState:UIControlStateNormal];
    [quxiao setTitle:@"取消" forState:UIControlStateNormal];
    
    
    
    [xiazai setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [zanting setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [huifu setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [quxiao setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
    [xiazai addTarget:self action:@selector(xiazai) forControlEvents:UIControlEventTouchUpInside];
    [zanting addTarget:self action:@selector(zanting) forControlEvents:UIControlEventTouchUpInside];
    [huifu addTarget:self action:@selector(huifu) forControlEvents:UIControlEventTouchUpInside];
    [quxiao addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
    
    
 
    
    
    
    [self.view addSubview:xiazai];
    [self.view addSubview:zanting];
    [self.view addSubview:huifu];
    [self.view addSubview:quxiao];
    
}
-(void)xiazai{
    NSLog(@"下载");
    //创建url
    NSString * strurl=textfield.text;
    
    strurl =[strurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    NSURL *url=[NSURL URLWithString:strurl];
    
    //创建请求
    NSURLRequest * request=[NSURLRequest requestWithURL:url];
    
    //创建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];
    
}
-(void)zanting{
    NSLog(@"暂停");
    [downloadTask suspend];
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    
}
-(void)huifu{
    NSLog(@"恢复");
    [downloadTask resume];
    if ([label.text isEqualToString:@""]) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    }else{
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    }
}
-(void)quxiao{
    NSLog(@"取消");
    progress.progress=0;
    [downloadTask cancel];
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    label.text=nil;
}
-(void)setjindutiaozhuangtai:(int64_t)zongliang setjindutiao:(int64_t)dangqianxiazailiang{
    
    //异步
    dispatch_async(dispatch_get_main_queue(), ^{
        progress.progress=(float)dangqianxiazailiang/zongliang;

        if (dangqianxiazailiang==zongliang) {
            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{
    
    
    
    [self setjindutiaozhuangtai:totalBytesExpectedToWrite setjindutiao:totalBytesWritten];
    
    NSLog(@"bytesWritten: %lld  totalBytesWritten:%lld   totalBytesExpectedToWrite:%lld ",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    
    NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    path=[path stringByAppendingPathComponent:@"图片01.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);
    }
    
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    if (error) {
        NSLog(@"%@",error);
    }
}

@end


转载于:https://my.oschina.net/u/2483781/blog/542238

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值