標籤:
iOS開發網路篇—檔案下載(二·合理)
一、邊下載,邊寫入
1.思路
把下載的data追加到檔案的尾部,直到所有的資料下載完為止。
1.在連通了伺服器的時候,建立一個空的檔案到沙箱中NSFileManager(檔案管理類)
2.建立寫資料的檔案控制代碼
3.在接收到伺服器返回的資料後,把data寫入到建立的空檔案中,但是不能使用writeTofile(會覆蓋)
3.1移動到檔案的尾部
3.2從當前移動的位置,寫入資料
4.伺服器的資料載入完畢後關閉串連,不再輸入資料在檔案中
二、程式碼範例
1 // 2 // YYViewController.m 3 // 01-檔案的下載(不合理) 4 // 5 // Created by apple on 14-6-30. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 // 8 9 #import "YYViewController.h"10 11 @interface YYViewController ()12 @property(nonatomic,strong)NSMutableData *fileData;13 @property(nonatomic,strong)NSFileHandle *writeHandle;14 - (IBAction)star;15 16 @end17 18 @implementation YYViewController19 20 - (void)viewDidLoad21 {22 [super viewDidLoad];23 }24 25 - (IBAction)star {26 //建立下載路徑27 28 NSURL *url=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/resources/videosres.zip"];29 30 //建立一個請求31 NSURLRequest *request=[NSURLRequest requestWithURL:url];32 33 //發送請求(使用代理的方式)34 NSURLConnection *connt=[NSURLConnection connectionWithRequest:request delegate:self];35 [connt start];36 }37 38 #pragma mark- NSURLConnectionDataDelegate代理方法39 /*40 *當接收到伺服器的響應(連通了伺服器)時會調用41 */42 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response43 {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 59 /*60 *當接收到伺服器的資料時會調用(可能會被調用多次,每次只傳遞部分資料)61 */62 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data63 {64 //一點一點接收資料。65 NSLog(@"接收到伺服器的資料!---%d",data.length);66 //把data寫入到建立的空檔案中,但是不能使用writeTofile(會覆蓋)67 //移動到檔案的尾部68 [self.writeHandle seekToEndOfFile];69 //從當前移動的位置,寫入資料70 [self.writeHandle writeData:data];71 }72 73 /*74 *當伺服器的資料載入完畢時就會調用75 */76 -(void)connectionDidFinishLoading:(NSURLConnection *)connection77 {78 NSLog(@"下載完畢");79 //關閉串連,不再輸入資料在檔案中80 [self.writeHandle closeFile];81 }82 /*83 *請求錯誤(失敗)的時候調用(請求逾時\斷網\沒有網\,一般指用戶端錯誤)84 */85 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error86 {87 }88 @end
注意點:
(1)建立檔案儲存體路徑(寫入到沙箱)
NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath=[caches stringByAppendingPathComponent:@"video.zip"];
(2)建立一個空的檔案夾( NSFileManager類的使用)
NSFileManager *mgr=[NSFileManager defaultManager];
(3)建立寫資料的檔案控制代碼
self.writeHandle=[NSFileHandle fileHandleForWritingAtPath:filePath];
(4)把data寫入到建立的空檔案中,但是不能使用writeTofile(會覆蓋)
移動控制代碼到檔案的尾部 [self.writeHandle seekToEndOfFile];
(5)下載完畢的時候,關閉串連
[self.writeHandle closeFile];
標籤: IOS開發, 網路篇
iOS開發 -檔案下載(2合理)