我想从网络服务下载一个 wav 文件,将其缓存在 iphone 上并使用 AVAudioPlayer 播放它。在处理相对较大的文件时,使用 NSFileHandle 和 NSURLConnection 似乎是一个可行的解决方案。但是,在模拟器中运行应用程序后,我在定义的目录(NSHomeDirectory/tmp)下看不到任何保存的文件。下面是我的基本代码。我在哪里做错了?任何想法表示赞赏!
#define TEMP_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"]
- (void)downloadToFile:(NSString*)name
{
NSString* filePath = [[NSString stringWithFormat:@"%@/%@.wav", TEMP_FOLDER, name] retain];
self.localFilePath = filePath;
// set up FileHandle
self.audioFile = [[NSFileHandle fileHandleForWritingAtPath:localFilePath] retain];
[filePath release];
// Open the connection
NSURLRequest* request = [NSURLRequest
requestWithURL:self.webURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#pragma mark -
#pragma mark NSURLConnection methods
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[self.audioFile writeData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(@"Connection failed to downloading sound: %@", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
[audioFile closeFile];
}