標籤:cache nsca mat 複製 非同步 path contents resources htm
最基本的網路檔案下載(使用原生的網路請求)
#pragma mark - 小檔案下載
// 方法一: NSData dataWithContentsOfURL- (void)downloadFile1{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 其實這就是一個GET請求 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/images/minion_01.png"]; NSData *data = [NSData dataWithContentsOfURL:url]; NSLog(@"%lu", data.length); });}
// 方法二: NSURLConnection- (void)downloadFile2{ NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/images/minion_01.png"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"%lu", data.length); }];}
//方法三:NSURLSession iOS7開始出現的 為取代NSURLConnection- (void)downloadFile3{ // 1.得到session對象 NSURLSession *session = [NSURLSession sharedSession]; // 2.建立一個下載task NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/test.mp4"]; NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {// location : 臨時檔案的路徑(下載好的檔案) NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; // response.suggestedFilename : 建議使用的檔案名稱,一般跟伺服器端的檔案名稱一致 NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; // 將臨時檔案剪下或者複製Caches檔案夾 NSFileManager *mgr = [NSFileManager defaultManager]; // AtPath : 剪下前的檔案路徑 // ToPath : 剪下後的檔案路徑 [mgr moveItemAtPath:location.path toPath:file error:nil]; }]; // 3.開始任務 [task resume];}
#pragma mark - 大檔案下載
//方法一: NSURLConnection (合理:單個線程 下載一點就寫入一點)使用NSFileHandle//控制代碼對象@property (nonatomic, strong) NSFileHandle * writeHandle;- (void)downloadFile4{ NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 下載(建立完conn對象後,會自動發起一個非同步請求,通過delegate回調下載資訊) [NSURLConnection connectionWithRequest:request delegate:self];}#pragma mark - NSURLConnectionDataDelegate- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{//請求失敗}// 1.接收到伺服器的響應就會調用- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ // 檔案路徑 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"]; // 建立一個空的檔案 到 沙箱中 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr createFileAtPath:filepath contents:nil attributes:nil]; // 建立一個用來寫資料的檔案控制代碼 self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];}// 2.當接收到伺服器返回的實體資料時調用(具體內容,這個方法可能會被調用多次)- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // 移動到檔案的最後面 [self.writeHandle seekToEndOfFile]; // 將資料寫入沙箱 [self.writeHandle writeData:data];}// 3.載入完畢後調用(伺服器的資料已經接收完畢)- (void)connectionDidFinishLoading:(NSURLConnection *)connection;{ // 關閉檔案 設定為空白 [self.writeHandle closeFile]; self.writeHandle = nil;}
//檔案流@property (nonatomic, strong) NSOutputStream * fileStream;//方法二: NSURLConnection 使用NSOutputStream- (void)downloadFile6{ NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 下載(建立完conn對象後,會自動發起一個非同步請求,通過delegate回調下載資訊) [NSURLConnection connectionWithRequest:request delegate:self];}#pragma mark - NSURLConnectionDataDelegate- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{//請求失敗}// 1.接收到伺服器的響應就會調用- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ // 檔案路徑 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"]; // 建立一個空的檔案 到 沙箱中 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr createFileAtPath:filepath contents:nil attributes:nil]; // 建立一個用來寫資料的檔案控制代碼 self.fileStream = [NSOutputStream outputStreamToFileAtPath:filepath append:YES];}// 2.當接收到伺服器返回的實體資料時調用(具體內容,這個方法可能會被調用多次)- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ //將資料追加到檔案流中 [self.fileStream write:data.bytes maxLength:data.length];}// 3.載入完畢後調用(伺服器的資料已經接收完畢)- (void)connectionDidFinishLoading:(NSURLConnection *)connection;{ // 關閉檔案流 [self.fileStream close];}
更多內容--> 部落格導航 每周一篇喲!!!
有任何關於iOS開發的問題!歡迎下方留言!!!或者郵件[email protected] 雖然我不一定能夠解答出來,但是我會請教iOS開發高手!!!解答您的問題!!!
檔案下載(NSURLConnection/NSURLSession)