I have an iPhone app that downloads multiple WAV files from the web, storing the resultant sound data on the phone for playback in the app. Sometimes this works fine, and sometimes I'm getting one of two problems with the sound:
1) There are pieces of a downloaded sound file that play back as staticky, corrupted noise
2) Sometimes the full download doesn't appear to happen, meaning the binary data isn't recognizable as a legit sound file and chokes my playback library (FMOD), causing a crash.
I'm using an NSURLConnection to build up the data by appending data received from the connection, as described in Apple's docs. My question is this: how can I write my downloading code so as to ensure that all files get downloaded and that they get downloaded without the corruption/noise?
Facts:
- The downloads are happening from Amazon S3.
- They are a maximum of around a half megabyte in size.
- They are not corrupted on the server -- i.e. they play back fine in a browser even when screwed up on the phone.
Below is the code I use to download all undownloaded files on each app launch. Thanks in advance for any help!
- (void)downloadOutstandingFileSounds{
NSArray *theFiles = [File listOfDownloadableOpponentfiles];
if ([theFiles count] > 0) {
NSLog(@"Updating %d new files...", [theFiles count]);
for (File *file in theFiles) {
self.theFile = file;
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:file.publicUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
currentFileDataContainer = [[NSMutableData data] retain];
}else {
NSLog(@"failed attempt to download resource at: %@", file.publicUrl);
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"OutstandingFileSoundsDownloaded" object:self];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[currentFileDataContainer setLength:0];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
[currentFileDataContainer release];
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data{
[currentFileDataContainer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Success! Received %d bytes of file data", [currentFileDataContainer length]);
self.theFile.fileSoundData = currentFileDataContainer;
[self.theFile save];
NSLog(@"Downloadable files count: %d", [[File listOfDownloadableOpponentfiles] count]);
self.theFile = nil;
[File clearCache];
}