iOS中 断点下载详解 韩俊强的博客

简介: 布局如下: 基本拖拉属性: #import "ViewController.h"#import "AFNetworking.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UILab...

布局如下:



基本拖拉属性:

#import "ViewController.h"
#import "AFNetworking.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (nonatomic, strong) AFHTTPRequestOperation *operation;

@end

@implementation ViewController



调用:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString *txtPath = [cachePath stringByAppendingPathComponent:@"mvTemp/mv.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:txtPath]) {
        self.progressView.progress = [[NSString stringWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil] floatValue];
        self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", _progressView.progress * 100];
        
    } else {
        self.progressView.progress = 0;
        self.progressLabel.text = @"0%";
    }
    NSLog(@"%@", NSHomeDirectory());
    
}

点击事件:

- (IBAction)startOrCancelDownLoad:(UIButton *)sender
{
    if ([sender.currentTitle isEqualToString:@"开始下载"]) {
        [sender setTitle:@"暂停下载" forState:UIControlStateNormal];
        
       
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString *filePath = [cachePath stringByAppendingPathComponent:@"mv"];
        NSString *tempPath = [cachePath stringByAppendingPathComponent:@"mvTemp"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:filePath]) {
            [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        if (![fileManager fileExistsAtPath:tempPath]) {
            [fileManager createDirectoryAtPath:tempPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *mp4TempPath = [tempPath stringByAppendingPathComponent:@"mv.temp"];
        NSString *txtTempPath = [tempPath stringByAppendingPathComponent:@"mv.txt"];
        NSString *mp4Path = [filePath stringByAppendingPathComponent:@"mv.mp4"];
        NSURL *url = [NSURL URLWithString:@"http://video.szzhangchu.com/1442395443772_5176326090.mp4"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        unsigned long long downLoadBytes = 0;
        if ([fileManager fileExistsAtPath:mp4TempPath]) {
            downLoadBytes = [self fileSizeAtPath:mp4TempPath];
            NSString *range = [NSString stringWithFormat:@"bytes=%llu-", downLoadBytes];
            NSMutableURLRequest *mutableRequest = [request mutableCopy];
            [mutableRequest setValue:range forHTTPHeaderField:@"Range"];
            request = mutableRequest;
        }
        if (![fileManager fileExistsAtPath:mp4Path]) {
            self.operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
            [self.operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:mp4TempPath append:YES]];
            __weak typeof(self) weakSelf = self;
            [_operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                weakSelf.progressView.progress = (float)(totalBytesRead + downLoadBytes) / (float)(totalBytesExpectedToRead + downLoadBytes);
                weakSelf.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", weakSelf.progressView.progress * 100];
                NSString *progress = [NSString stringWithFormat:@"%.3f", weakSelf.progressView.progress];
                [progress writeToFile:txtTempPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
            }];
            
            [_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [fileManager moveItemAtPath:mp4TempPath toPath:mp4Path error:nil];
                [fileManager removeItemAtPath:txtTempPath error:nil];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
            
            [_operation start];
        }
        
    } else {
        [sender setTitle:@"开始下载" forState:UIControlStateNormal];
        [self.operation cancel];
        _operation = nil;
    }
    
    
    
}

- (unsigned long long)fileSizeAtPath:(NSString *)path
{
    unsigned long long fileSize = 0;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *dict = [fileManager attributesOfItemAtPath:path error:&error];
        if (dict && !error) {
            fileSize = [dict fileSize];
        }
    }
    return fileSize;
}

最终效果如下:


用到的第三方数据请求:AFNetworking,大家应该都有,这里不做介绍


关注博主微博每日更新技术:http://weibo.com/hanjunqiang



目录
相关文章
|
网络安全 开发者 iOS开发
iOS技术博客:App备案指南
本文介绍了移动应用程序(App)备案的重要性和流程。备案是规范App开发和运营的必要手段,有助于保护用户权益、维护网络安全和社会秩序。为了帮助开发者更好地了解备案流程,本文提供了一份最新、最全、最详的备案指南,包括备案目的、好处、对象、时间、流程、条件和注意事项等内容。
iOS技术博客:App备案指南
|
数据采集 网络协议 开发工具
如何进行iOS技术博客的备案?
如何进行iOS技术博客的备案?
453 2
|
数据采集 网络协议 开发工具
 如何进行iOS技术博客的备案?
在本篇问答中,我们将为iOS技术博主介绍如何进行备案。如果你的iOS应用只包含简单的页面,并通过蓝牙进行数据采集和传输,那么你可能不需要备案。然而,如果你希望通过域名调用后端服务,建议进行备案以满足国内服务器访问的要求。我们将详细解释备案的三要素以及备案流程,并提供参考资料供你查阅。
|
Web App开发 Dart 安全
flutter制作博客展示平台,现已支持 Web、macOS 应用、Android 和 iOS
Flutter Blog Theme using Flutter | Web, macOS, Android, iOS Flutter 最近发布了 Flutter V2.5.1,其性能得到了很大提升,支持 Web、macOS、Android 和 iOS。 这就是为什么今天我们使用在 Web、macOS 应用、Android 和 iOS 应用上运行的 flutter 创建响应式博客主题。 此外,我们创建了一个具有自定义悬停动画的动画网络菜单。 最后,您将学习如何使用 Flutter 制作响应式应用程序。
748 0
flutter制作博客展示平台,现已支持 Web、macOS 应用、Android 和 iOS
|
定位技术 iOS开发
iOS中 百度地图详解 韩俊强的博文
需要准备工作按照下图引进类库 需要添加 添加的两个字符串为:NSLocationWhenInUseUsageDescription  /  NSLocationAlwaysUsageDescription 默认定位设置: 设置工作准备完毕上代码: 指示根视图: ...
926 0
|
iOS开发 索引
iOS中 NSString的几种常用方法 韩俊强的博客
要把 “2011-11-29” 改写成 “2011/11/29”一开始想用ios的时间格式,后来用NSString的方法搞定。 1.创建NSString字符串 NSString 与 char* 最大的区别就是 NSString是一个objective对象,而char* 是一个字节数组。
1053 0
|
iOS开发
IOS小工具以及精彩的博客
IOS小工具以及精彩的博客 工具Log Guru是一个收集Log的小工具, 可以在 Mac 上查看 iOS 设备的实时系统日志. 现在可以直接高亮显示在 FIR.im 上安装 app 失败的原因。后续会增加各种进程过滤、高亮某进程、只看 Error level 等功能。
1356 0
|
iOS开发 存储
iOS开发网络篇—大文件的多线程断点下载
iOS开发网络篇—多线程断点下载 说明:本文介绍多线程断点下载。项目中使用了苹果自带的类,实现了同时开启多条线程下载一个较大的文件。因为实现过程较为复杂,所以下面贴出完整的代码。 实现思路:下载开始,创建一个和要下载的文件大小相同的文件(如果要下载的文件为100M,那么就在沙盒中创建一个100M的文件,然后计算每一段的下载量,开启多条线程下载各段的数据,分别写入对应的文件部分)。
1151 0
|
Web App开发 iOS开发
IOS开发博客学习
M了个J :http://www.cnblogs.com/mjios/tag/objective-c/ http://www.cnblogs.com/tianjian/p/3358602.html  Cocos2d-x  VS环境配置  泰然论坛:http://www.
862 0
|
iOS开发
IOS学习博客不错的大部分是原创
http://blog.csdn.net/iukey/article/category/955062
769 0

热门文章

最新文章