views:

169

answers:

2

Hi all, 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
                             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];

}
+1  A: 

NSFileHandle fileHandleForWritingAtPath: requires the file to already exist. How are you creating the file?

David Gelhar
I knew it would turn out to be something silly. I didn't know that though. Now I'm getting the file after I set up the NSFileManager. Thanks man!
Jinru
A: 

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.

Jordan