2012-05-08 37 views
0

我需要通过我的应用程序从互联网下载一个mp3文件,我发现了一个解决方案,使用NSURLConnection和连接请求。这里是我的代码(代码从另一个常见问题)将NSURLConnection异步下载的数据保存到iPhone的本地文件?

- (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本地文件?

回答

0

所以我发现了一个很长的谷歌搜索后的溶液,其我忘记添加代码

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

    [responseData writeToFile:fileName atomically:YES]; 

三江源