How to download a wav file from the web to a location on iPhone using NSFileHandle and NSURLConnection?
I want to download a wav file from a web service, cache it on the iphone and playback it using AVAudioPlayer. Using NSFileHandle and NSURLConnection seems a viable solution when dealing with relatively large files. However, after running the app in the simulator I don't see any saved file under the defined directory (NSHomeDirectory/tmp). Below is my basic code. Where am I doing wrong? Any thoughts are appreciated!
#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
开发者_如何学GotimeoutInterval: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];
}
NSFileHandle fileHandleForWritingAtPath:
requires the file to already exist. How are you creating the file?
Where is your
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
delegate?
this is where you should write/save the file.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
this is where you append the data you receive.
精彩评论