NSURLConnection异步下载的数据保存到iPhone的本地文件?

时间:2012-05-08 10:14:58

标签: download nsurlconnection asynchronous

我需要通过我的应用程序从互联网上下载一个mp3文件,我找到了一个解决方案,使用NSURLConnection和连接请求。这是我的代码(来自另一个常见问题的代码)

 - (IBAction)downloadData:(id)sender
 {
    NSURL *myURL = [NSURL URLWithString:@"http://www.example.org/mp3song"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

   [[NSURLConnection alloc] initWithRequest:request delegate:self];
 }


 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
 {
   responseData = [[NSMutableData alloc] init];
 }


 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
 {
   [responseData appendData:data];
 }


  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
  {
   [responseData release];
   [connection release];

  }


 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
 {
    NSLog(@"Succeeded! Received %d bytes of data",[responseData
                                               length]);

    NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
 }

我如何将此响应数据mp3文件保存到我的本地iPhone文件中?

1 个答案:

答案 0 :(得分:0)

所以我在漫长的谷歌搜索后找到了解决方案,我忘了添加代码

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];

   [responseData writeToFile:fileName atomically:YES];

三江源