依靠NSOutputStream,NSURLSession,NSURLSessionDataTask创建一个支持断点下载的任务

本文介绍了一个iOS应用中实现断点续传下载功能的方法。通过NSURLSessionDataDelegate接口,利用NSOutputStream进行文件写入,实现了从上次下载的位置继续下载的功能,并记录了已下载的数据量。此外,还介绍了如何使用plist文件保存文件的总大小,以便于下次启动应用时能够正确地显示进度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//
//  ViewController.m
//  BreakPointDownload
//
//  Created by hq on 16/4/18.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"
#import "NSString+Hash.h"

//定义文件等下载路径cache路径
#define HQFilePath NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject

#define HQFileURLString @"http://xxx/resources/videos/minion_01.mp4"


//定义我们的文件名,直接只用url因为每个url对应一个文件是唯一的
#define HQFileName HQFileURLString.md5String


@interface ViewController () <NSURLSessionDataDelegate>

@property (weak, nonatomic) IBOutlet UILabel *downloadStatus;
@property (weak, nonatomic) IBOutlet UIProgressView *pro;
@property (weak, nonatomic) IBOutlet UILabel *downSize;

@property (weak, nonatomic) IBOutlet UIButton *loadBut;

//文件等总大小
@property(nonatomic,assign) NSInteger fileTotalSize;
//当前文件下载了多少
@property(nonatomic,assign) NSInteger fileCurrentSize;


@property(nonatomic,strong) NSOutputStream *outputStream;

@property(nonatomic,strong) NSURLSessionDataTask *task;


- (IBAction)butClicked:(UIButton *)sender;

@property(nonatomic,strong) NSOperationQueue *queue;

@end

@implementation ViewController


-(NSURLSessionDataTask *)task{
    
    if (!_task) {
      
        NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:HQFileURLString]];
        
        //指定从哪个位置继续下载
        [request setValue:[NSString stringWithFormat:@"bytes=%ld-",[self getCurrentDownloadSize]] forHTTPHeaderField:@"Range"];
        
        _task=[session dataTaskWithRequest:request];
        
    }
    
    return _task;
}



-(NSOutputStream *)outputStream{
    
    if (!_outputStream) {
       
        _outputStream=[[NSOutputStream alloc]initToFileAtPath:[HQFilePath stringByAppendingPathComponent:HQFileName] append:YES];
    }
    return _outputStream;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    
    NSString *plistPath=[HQFilePath stringByAppendingPathComponent:@"fileSize.plist"];
    
    //获取文件的总大小
    NSInteger totalSize=[[NSDictionary dictionaryWithContentsOfFile:plistPath][HQFileName] integerValue];
    
    if (totalSize==0) {
        self.downSize.hidden=YES;
        self.pro.progress=0;
    }
    else{
        self.downSize.hidden=NO;
        self.downSize.text=[NSString stringWithFormat:@"%.0f%",1.0*[self getCurrentDownloadSize]/totalSize*100];
        self.pro.progress=1.0*[self getCurrentDownloadSize]/totalSize;
    }

    
    if (totalSize==[self getCurrentDownloadSize]&&totalSize!=0) {
        
        self.downloadStatus.hidden=NO;
        
        self.loadBut.enabled=NO;
        
        [self.loadBut setTitle:@"开始下载" forState:UIControlStateNormal];
        
    }
    
    NSLog(@"%@",[HQFilePath stringByAppendingPathComponent:HQFileName]);

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (IBAction)butClicked:(UIButton *)sender {
    
    if ([self.loadBut.titleLabel.text isEqualToString:@"开始下载"]) {
       
        [self.task resume];
        
        [self.loadBut setTitle:@"暂停" forState:UIControlStateNormal];
        
    }
    else if([self.loadBut.titleLabel.text isEqualToString:@"暂停"]){
        
        [self.task suspend];
        
        [self.loadBut setTitle:@"继续下载" forState:UIControlStateNormal];
        
    }
    else{
        
       [self.task resume];
       [self.loadBut setTitle:@"暂停" forState:UIControlStateNormal];
        
    }
    
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    
    [self.outputStream open];
    
    //必须开启才能接收服务端的请求
    completionHandler(NSURLSessionResponseAllow);
    
    //表示服务器当前能返回给我们的文件等大小
    self.fileTotalSize=[response.allHeaderFields[@"Content-Length"] integerValue]+[self getCurrentDownloadSize];

    //把文件的总大小写入我们的plist文件,key就用我们的文件名
    NSString *plistPath=[HQFilePath stringByAppendingPathComponent:@"fileSize.plist"];
    
    NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
    if (dict==nil) {
        dict=[NSMutableDictionary dictionary];
    }
    //用我们的md5的url当作key
    dict[HQFileName]=@(self.fileTotalSize);
    
    [dict writeToFile:plistPath atomically:YES];
    
    
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
    
    [self.outputStream write:[data bytes] maxLength:data.length];
    
    self.fileCurrentSize=[self getCurrentDownloadSize];
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        
        self.downSize.hidden=NO;
        
        self.pro.progress=(1.0*self.fileCurrentSize/self.fileTotalSize);
        
        self.downSize.text=[NSString stringWithFormat:@"%.0f%%",(1.0*self.fileCurrentSize/self.fileTotalSize)*100];
        
    }];

    NSLog(@"%ld",self.fileCurrentSize);
    
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    if (error) {
        return;
    }
    
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    
        self.downloadStatus.hidden=NO;
        
        self.loadBut.enabled=NO;
        
        [self.loadBut setTitle:@"开始下载" forState:UIControlStateNormal];
    }];
    
    [self.outputStream close];
    self.outputStream=nil;
    
    self.task=nil;
    
}

//判断文件现在已经下载了多少
-(NSInteger) getCurrentDownloadSize{
    
    NSDictionary *dict=[[NSFileManager defaultManager] attributesOfItemAtPath:[HQFilePath stringByAppendingPathComponent:HQFileName] error:nil];
    
    return [dict[@"NSFileSize"] integerValue];
    
}


@end





内容概要:本文针对国内加密货币市场预测研究较少的现状,采用BP神经网络构建了CCi30指数预测模型。研究选取2018年3月1日至2019年3月26日共391天的数据作为样本,通过“试凑法”确定最优隐结点数目,建立三层BP神经网络模型对CCi30指数收盘价进行预测。论文详细介绍了数据预处理、模型构建、训练及评估过程,包括数据归一化、特征工程、模型架构设计(如输入层、隐藏层、输出层)、模型编译与训练、模型评估(如RMSE、MAE计算)以及结果可视化。研究表明,该模型在短期内能较准确地预测指数变化趋势。此外,文章还讨论了隐层节点数的优化方法及其对预测性能的影响,并提出了若干改进建议,如引入更多技术指标、优化模型架构、尝试其他时序模型等。 适合人群:对加密货币市场预测感兴趣的研究人员、投资者及具备一定编程基础的数据分析师。 使用场景及目标:①为加密货币市场投资者提供一种新的预测工具和方法;②帮助研究人员理解BP神经网络在时间序列预测中的应用;③为后续研究提供改进方向,如数据增强、模型优化、特征工程等。 其他说明:尽管该模型在短期内表现出良好的预测性能,但仍存在一定局限性,如样本量较小、未考虑外部因素影响等。因此,在实际应用中需谨慎对待模型预测结果,并结合其他分析工具共同决策。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值