NSURL*url=[NSURLURLWithString:@"http://119.147.106.249/gdown_group11/M00/3F/15/d5Nq-UxBq88AAAAAAUn8QBO4rlY4306605/01_01_Android%E5%B9%B3%E5%8F%B0%E4%B8%80%E6%97%A5%E6%B8%B8.mp4?k=-4hoIXm9CXQ_Zo79EQprcQ&t=1346820047&u=3662410469-66934941-bei9apjt&s=307200&file=01_01_Android%E5%B9%B3%E5%8F%B0%E4%B8%80%E6%97%A5%E6%B8%B8.mp4"];
NSURLRequest*request=[[NSURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:100.0];//设置缓存和超时
NSURLConnection*connection=nil;
connection=[[NSURLConnectionalloc]initWithRequest:requestdelegate:selfstartImmediately:YES];
//初始化connection对象并马上执行,有的初始化方法并不是马上开始执行,而需要调用start方法。
二、实现connection的回调方法:-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response
{ //该方法在响应connection时调用
NSLog(@"response");
self.data=[[NSMutableDataalloc]init];
NSHTTPURLResponse*httpResponse=(NSHTTPURLResponse*)response;
if(httpResponse&&[httpResponserespondsToSelector:@selector(allHeaderFields)]){
NSDictionary*httpResponseHeaderFields=[httpResponseallHeaderFields];
mFileSize=[[httpResponseHeaderFieldsobjectForKey:@"Content-Length"]longLongValue];
}//获取文件文件的大小
}
-(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error
{//出错时调用
NSLog(@"error");
}
-(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data
{//接受数据,在接受完成之前,该方法重复调用
NSLog(@"receive");
[_dataappendData:data];
_displayLabel.text=[NSStringstringWithFormat:(@"%6.1fkb/%6.1fkb"),[_datalength]/1024.0,mFileSize/1024.0];
[_progressViewsetProgress:[_datalength]/(float)mFileSize];
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{//完成时调用
NSLog(@"Finish");
NSString*filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]stringByAppendingPathComponent:@"android.mp4"];
[_datawriteToFile:filePathatomically:NO];//将数据写入Documents目录。
NSLog(@"%@",filePath);
}
//郑文亮 IPhone Head