標籤:注意 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(大檔案下載)