標籤:
iOS開發網路篇—檔案下載(一·不合理)
一、小檔案下載
如果檔案比較小,下載方式會比較多
直接用NSData的+ (id)dataWithContentsOfURL:(NSURL *)url;
利?NSURLConnection發送一個HTTP請求去下載
如果是下載圖片,還可以利用SDWebImage架構
二、沙箱
1.在finder中,系統的一些檔案(資產庫)是隱藏的,可以通過在終端啟動並執行代碼,顯示隱藏的檔案。
顯示隱藏系統檔案:
defaults write com.apple.finder AppleShowAllFiles YES
2.製作替身,以便查看應用沙箱。
推薦工具,SimPholders,可以用來查看沙箱。
三、大檔案下載樣本
提示:該項目代碼,僅為樣本,並不合理。
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 - (IBAction)star;14 15 @end16 17 @implementation YYViewController18 19 - (void)viewDidLoad20 {21 [super viewDidLoad];22 }23 24 - (IBAction)star {25 //建立下載路徑26 27 NSURL *url=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/resources/videosres.zip"];28 29 //建立一個請求30 NSURLRequest *request=[NSURLRequest requestWithURL:url];31 32 //發送請求(使用代理的方式)33 NSURLConnection *connt=[NSURLConnection connectionWithRequest:request delegate:self];34 [connt start];35 }36 37 #pragma mark- NSURLConnectionDataDelegate代理方法38 /*39 *當接收到伺服器的響應(連通了伺服器)時會調用40 */41 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response42 {43 //初始化data44 self.fileData=[NSMutableData data];45 }46 47 /*48 *當接收到伺服器的資料時會調用(可能會被調用多次,每次只傳遞部分資料)49 */50 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data51 {52 //一點一點接收資料。53 NSLog(@"接收到伺服器的資料!---%d",data.length);54 [self.fileData appendData:data];55 }56 57 /*58 *當伺服器的資料載入完畢時就會調用59 */60 -(void)connectionDidFinishLoading:(NSURLConnection *)connection61 {62 // 下載完畢63 // 大檔案不放Documents, 可以放Library\Caches或者tmp64 // NSString *fullpath=[caches stringByAppendingString:@"video.zip"];65 66 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];67 NSString *filepath = [caches stringByAppendingPathComponent:@"video.zip"];68 [self.fileData writeToFile:filepath atomically:YES];69 70 NSLog(@"下載完畢");71 }72 /*73 *請求錯誤(失敗)的時候調用(請求逾時\斷網\沒有網\,一般指用戶端錯誤)74 */75 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error76 {77 }78 79 @end
模擬器:
點擊螢幕上得點擊下載按鈕,下載在本機伺服器上的檔案。
代碼說明:
在處理大檔案下載問題上,無論使用同步或者非同步方式下載,都是一次性拿到所有的資料,不可取。所以更合適的是使用代理的方式進行處理。
這個項目中,花了很長的時間在拼接資料上,此外又花費了很長的時間放在了寫入系統沙箱上。且會佔用大量的記憶體空間。這種方法是不合理的,更合適的方法應該是一邊拼接資料,一邊寫入硬碟。
iOS開發 -檔案下載(1不合理)