用NSURLSession发送网络请求

43 篇文章 0 订阅
具体代码如下:
#define KfullPath  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"hzk.mp4"]
#define KSizefullPath  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"hzk.hzk"]
@interface ViewController ()<NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (nonatomic ,strong)NSURLSessionDataTask *dataTask;
@property (nonatomic ,assign)NSInteger totalSize;
@property (nonatomic ,assign)NSInteger currentSize;
/** 文件句柄 */
@property (nonatomic ,strong)NSFileHandle *handle;
@property (nonatomic ,strong) NSURLSession *session;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:KfullPath error:nil];
    NSLog(@"%@",fileInfo);
    
    self.currentSize = [fileInfo fileSize];
    
    NSData *totalSizeData = [NSData dataWithContentsOfFile:KSizefullPath];
    NSInteger totalSize = [[NSString alloc] initWithData:totalSizeData encoding:NSUTF8StringEncoding].integerValue;
    
    if (totalSize != 0) {
        self.progressView.progress = 1.0 * self.currentSize / totalSize;
    }
    NSLog(@"%@",KfullPath);
  
}
#pragma mark ----------------------
#pragma mark lazy loading

- (NSURLSession *)session
{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}
- (NSURLSessionDataTask *)dataTask
{
    if (!_dataTask) {
        NSURL *url =[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        NSString *headerStr = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize];
        [request setValue:headerStr forHTTPHeaderField:@"Range"];
        
        _dataTask = [self.session dataTaskWithRequest:request];
    
        
    }
    return _dataTask;
}
- (IBAction)startBtnClick:(id)sender {
    
    [self.dataTask resume];
}
- (IBAction)supenpBtnClick:(id)sender {
    
    [self.dataTask suspend];
}
- (IBAction)cancelBtnClick:(id)sender {
    [self.dataTask cancel];
    
      self.dataTask = nil;
}
- (IBAction)resumeBtnClick:(id)sender {
    
    [self.dataTask resume];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    self.totalSize = response.expectedContentLength + self.currentSize;
    
    //保存文件的总大小数据到磁盘里面
    NSData *totalSizeData = [[NSString stringWithFormat:@"%zd",self.totalSize] dataUsingEncoding:NSUTF8StringEncoding];
    [totalSizeData writeToFile:KSizefullPath atomically:YES];
    
    if (self.currentSize == 0) {
        [[NSFileManager defaultManager] createFileAtPath:KfullPath contents:nil attributes:nil];
    }
    NSFileHandle *handle =[NSFileHandle fileHandleForWritingAtPath:KfullPath];
    self.handle = handle;
    
    [handle seekToEndOfFile];
    
    completionHandler(NSURLSessionResponseAllow);
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.handle writeData:data];
    
    self.currentSize += data.length;
    
    self.progressView.progress = 1.0 *self.currentSize / self.totalSize;
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    [self.handle closeFile];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值