標籤:
一、實現下載檔案進度控制
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.顯示
模擬器顯示:
列印查看:
標籤: IOS開發, 網路篇
iOS開發 -檔案下載(3 進度條)