1

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];

}
saurb
  • 685
  • 1
  • 13
  • 24

2 Answers2

3

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

David Gelhar
  • 27,873
  • 3
  • 67
  • 84
  • 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! – saurb Mar 29 '10 at 00:31
  • +1. Interesting that it wouldn't throw an error or anything... I wonder what it was doing with all that data. – ajacian81 Feb 22 '11 at 08:27
0

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
  • 21,746
  • 10
  • 51
  • 63