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

StackOverflow https://stackoverflow.com/questions/2535001

문제

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

}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top