iOS 下载

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()
 4 @property (strong, nonatomic) NSMutableData *data;
 5 @end
 6 
 7 @implementation ViewController
 8 
 9 - (void)viewDidLoad
10 {
11     [super viewDidLoad];
12     // Do any additional setup after loading the view, typically from a nib.
13     NSString *url = @"";
14     url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
15     NSURL *newUrl = [NSURL URLWithString:url];
16     
17     NSURLRequest*request=[[NSURLRequest alloc]initWithURL:newUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:100.0];//设置缓存和超时
18     
19     NSURLConnection*connection=nil;
20     
21     connection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
22 }
23 
24 -(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
25 
26 {//该方法在响应connection时调用
27     
28     NSLog(@"response");
29     
30     self.data=[[NSMutableData alloc]init];
31     
32     NSHTTPURLResponse*httpResponse=(NSHTTPURLResponse*)response;
33     
34     if(httpResponse&&[httpResponse respondsToSelector:@selector(allHeaderFields)]){
35         
36         NSDictionary*httpResponseHeaderFields=[httpResponse allHeaderFields];
37         
38         //mFileSize=[[httpResponseHeaderFields objectForKey:@"Content-Length"]longLongValue];
39         
40     }//获取文件文件的大小
41     
42 }
43 
44 -(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
45 
46 {//出错时调用
47     
48     NSLog(@"error");
49 }
50 
51 -(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
52 
53 {//接受数据,在接受完成之前,该方法重复调用
54     
55     NSLog(@"receive");
56     
57     [self.data appendData:data];
58 //    
59 //    _displayLabel.text=[NSString stringWithFormat:(@"%6.1fkb/%6.1fkb"),[_datalength]/1024.0,mFileSize/1024.0];
60 //    
61 //    [_progressViewsetProgress:[_datalength]/(float)mFileSize];
62     
63 }
64 
65 -(void)connectionDidFinishLoading:(NSURLConnection*)connection
66 
67 {//完成时调用
68     
69     NSLog(@"Finish");
70     
71     NSString*filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]stringByAppendingPathComponent:@"android.mp3"];
72     
73     [_data writeToFile:filePath atomically:NO];//将数据写入Documents目录。
74     
75     NSLog(@"%@",filePath);
76     
77 }

 

posted on 2014-04-25 11:18  Hai_阔天空  阅读(258)  评论(0编辑  收藏  举报

导航