iOS开发网络篇—文件下载(三·进度条)

来源:互联网 发布:直布罗陀 知乎 编辑:程序博客网 时间:2024/04/28 06:30

iOS开发网络篇—文件下载(三·进度条) 

一、实现下载文件进度控制

1.代码示例

  1 #import "YYViewController.h"  2   3 @interface YYViewController ()  4 @property(nonatomic,strong)NSMutableData *fileData;  5 @property(nonatomic,strong)NSFileHandle *writeHandle;  6 @property(nonatomic,assign)long long currentLength;  7 @property(nonatomic,assign)long long sumLength;  8 @property (weak, nonatomic) IBOutlet UIProgressView *progress;  9  10 - (IBAction)star; 11  12 @end 13  14 @implementation YYViewController 15  16 - (void)viewDidLoad 17 { 18     [super viewDidLoad]; 19 } 20  21 - (IBAction)star { 22      23      24     //创建下载路径 25      26     NSURL *url=[NSURL URLWithString:@"http://192.168.0.109:8080/MJServer/resources/video.zip"]; 27      28     //创建一个请求 29     NSURLRequest *request=[NSURLRequest requestWithURL:url]; 30      31     //发送请求(使用代理的方式) 32 //    NSURLConnection *connt= 33     [NSURLConnection connectionWithRequest:request delegate:self]; 34 //    [connt start]; 35    36 } 37  38 #pragma mark- NSURLConnectionDataDelegate代理方法 39 /* 40  *当接收到服务器的响应(连通了服务器)时会调用 41  */ 42 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 43 { 44     //1.创建文件存储路径 45     NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 46     NSString *filePath=[caches stringByAppendingPathComponent:@"video.zip"]; 47  48      49      50     //2.创建一个空的文件,到沙盒中 51     NSFileManager *mgr=[NSFileManager defaultManager]; 52     //刚创建完毕的大小是o字节 53     [mgr createFileAtPath:filePath contents:nil attributes:nil]; 54      55     //3.创建写数据的文件句柄 56     self.writeHandle=[NSFileHandle fileHandleForWritingAtPath:filePath]; 57      58     //4.获取完整的文件的长度 59     self.sumLength=response.expectedContentLength; 60 } 61  62 /* 63  *当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据) 64  */ 65 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 66 { 67     //累加接收到的数据 68     self.currentLength+=data.length; 69      70     //计算当前进度(转换为double型的) 71     double progress=(double)self.currentLength/self.sumLength; 72     self.progress.progress=progress; 73      74     //一点一点接收数据。 75     NSLog(@"接收到服务器的数据!---%d",data.length); 76      77     //把data写入到创建的空文件中,但是不能使用writeTofile(会覆盖) 78     //移动到文件的尾部 79     [self.writeHandle seekToEndOfFile]; 80     //从当前移动的位置,写入数据 81     [self.writeHandle writeData:data]; 82 } 83  84 /* 85  *当服务器的数据加载完毕时就会调用 86  */ 87 -(void)connectionDidFinishLoading:(NSURLConnection *)connection 88 { 89     NSLog(@"下载完毕"); 90      91     //关闭连接,不再输入数据在文件中 92     [self.writeHandle closeFile]; 93     //销毁 94     self.writeHandle=nil; 95      96     //在下载完毕后,对进度进行清空 97     self.currentLength=0; 98     self.sumLength=0; 99     100     101 }102 /*103  *请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)104  */105 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error106 {107 }108 @end

2.显示

模拟器显示:

打印查看:

0 0