IOS NSURLConnection(大檔案下載)

來源:互聯網
上載者:User

標籤:注意   dir   resources   sop   cache   nsurl   manager   nec   led   

 

一、大檔案下載


1.方案:利用NSURLConnection和它的代理方法
1> 發送一個請求
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"];
// 2.請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.下載(建立完conn對象後,會自動發起一個非同步請求)
[NSURLConnection connectionWithRequest:request delegate:self];

2> 在代理方法中處理伺服器返回的資料
/**
 在接收到伺服器的響應時:
 1.建立一個空的檔案
 2.用一個控制代碼對象關聯這個空的檔案,目的是:方便後面用控制代碼對象往檔案後面寫資料
 */
- (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];
}

/**
 在接收到伺服器返回的檔案資料時,利用控制代碼對象往檔案的最後面追加資料
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 移動到檔案的最後面
    [self.writeHandle seekToEndOfFile];
    
    // 將資料寫入沙箱
    [self.writeHandle writeData:data];
}

/**
 在所有資料接收完畢時,關閉控制代碼對象
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 關閉檔案
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

2.注意點:千萬不能用NSMutableData來拼接伺服器返回的資料


二、NSURLConnection發送非同步請求的方法


1.block形式 - 除開大檔案下載以外的操作,都可以用這種形式
[NSURLConnection sendAsynchronousRequest:<#(NSURLRequest *)#> queue:<#(NSOperationQueue *)#> completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    
}];

2.代理形式 - 一般用在大檔案下載
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login?username=123&pwd=123"];
// 2.請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.下載(建立完conn對象後,會自動發起一個非同步請求)
[NSURLConnection connectionWithRequest:request delegate:self];

IOS NSURLConnection(大檔案下載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.