How to download a wav file from the web to a location on iPhone using NSFileHandle and NSURLConnecti

Posted by Jinru on Stack Overflow See other posts from Stack Overflow or by Jinru
Published on 2010-03-28T23:25:19Z Indexed on 2010/03/29 0:13 UTC
Read the original article Hit count: 730

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

}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about nsurlconnection