逻辑:
首先创建一个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];
}