我有一个iPhone应用程序可以从网上下载多个WAV文件,将结果声音数据存储在手机上,以便在应用程序中播放。有时这很好用,有时我会听到声音的两个问题之一:
1)有一些下载的声音文件可以播放为严重的,破坏的噪音
2)有时完全下载似乎不会发生,这意味着二进制数据无法识别为合法的声音文件并扼杀我的播放库(FMOD),从而导致崩溃。
我正在使用NSURLConnection通过附加从连接接收的数据来构建数据,如Apple的文档中所述。我的问题是:如何编写我的下载代码,以确保下载所有文件并下载它们而不会出现损坏/噪音?
事实:
以下是我在每个应用启动时下载所有未下载文件的代码。在此先感谢您的帮助!
- (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];
}
答案 0 :(得分:1)
我看不出你的方法有什么问题,但看看ASIHTTPRequest库http://allseeing-i.com/ASIHTTPRequest/这可以用来排队一些下载并管理错误。