我想从Web服务下载一个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];
}
答案 0 :(得分:3)
NSFileHandle fileHandleForWritingAtPath:
要求该文件已存在。你是如何创建文件的?
答案 1 :(得分:0)
你的
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
委托?
这是你应该写/保存文件的地方。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
这是您附加收到的数据的地方。