2010-05-24 38 views
1

我有一款iPhone應用程序可以從網絡上下載多個WAV文件,將結果聲音數據存儲在手機上供在應用程序中播放。有時候這工作得很好,有時我得到的兩個問題的聲音之一:在iPhone上下載/播放靜態音頻文件

1)有一個下載的聲音文件的各個部分是播放作爲staticky,損壞的噪音

2)有時全下載似乎不會發生,這意味着二進制數據不可識別爲合法的聲音文件,並扼殺我的播放庫(FMOD),導致崩潰。

我正在使用NSURLConnection通過附加從連接接收的數據來構建數據,如Apple的文檔中所述。我的問題是:我如何編寫我的下載代碼,以確保所有文件都得到下載,並且它們在沒有損壞/噪音的情況下被下載?

事實:

  • 下載是從Amazon S3發生。
  • 它們的大小最多爲半個兆字節。
  • 它們在服務器上沒有損壞 - 即使它們在手機上搞砸了,它們在瀏覽器中播放也很好。

下面是我用來下載每個應用程序啓動時所有未下載的文件的代碼。預先感謝任何幫助!

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

回答

1

我看不出什麼太不好的做法,但看看ASIHTTPRequest庫http://allseeing-i.com/ASIHTTPRequest/這可以用來排隊的一些下載和管理的錯誤。

+0

很酷。我曾經使用過ASI,但從來沒有需要它來解決這個問題。我喜歡ASI的操作隊列方面,但我認爲它的gzip支持可能是真正的東西,可能可以解決我的問題在這裏 - 感謝指出我回到它。 – trevrosen 2010-05-24 15:39:32

+0

順便說一句,你似乎已經問了一些問題,但沒有接受任何答案。你應該回頭看看你所提出的問題,並接受正確的答案(假設有一個答案):這就是本網站的內容! – Andiih 2010-05-24 17:30:29

+0

這就是「回答你的問題」按鈕的意思嗎?我正在尋找如何做到這一點(接受)。我會更難看。 :-) ASI竟然爲我解決這個問題。我沒有看過代碼,但我懷疑它只是在傳輸過程中更好地解決了錯誤。 ASINetworkQueue類非常好。我一定會更經常地使用這個庫。它甚至對S3 API進行了初步支持! – trevrosen 2010-05-26 14:15:08