邏輯:
首先建立一個NSURL地址,發送request請求,然後調用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData
*)data
把下載的資料存放區到NSDate對象中,當下載完成後執行
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 方法,
假如串連出現錯誤:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
實現:
//定義一個NSDate對象NSMutableData *buffer;/*=========------------------==============*/- (void)viewDidLoad{ //調用down方法 [self Down]; //初始化 buffer buffer = [[NSMutableData alloc]init]; [super viewDidLoad];}-(void) Down{ //建立url NSURL *url = [NSURL URLWithString:@"http://192.168.67.3:8080/movie/3.mp4"]; //基於http的串連請求 NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url]; //建立 connection 會話NSURLConnection* connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; //釋放[connection release];[request release];}//提供一個NSData, 封裝了剛從串連上收到的位元組塊//下載添加資料的時候會產生一個資料回調(它是一部分一部分的下載),直到資料全部下載完成- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data{ //buffer 是一個可以修改的data 資料,把從網路上下載的資料 data 添加進去[buffer appendData:data];}//基於http的會話已經完成會執行(就是下載完成)- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ //建立一個檔案, 指定路徑,名稱,和內容 [[NSFileManager defaultManager]createFileAtPath:@"/tmp/movie.mp4" contents:buffer attributes:nil];}//當網路連接不成功或出現異常的時候會調用,提供一個NSError以解釋失敗的原因- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //載入的是一個警告框UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle: [error localizedDescription] message: [error localizedFailureReason] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];[errorAlert show];[errorAlert release];}