2012-07-17 58 views
1

我有這段代碼從服務器下載mp3。所有設置都使用Table View解析播客,而mp3的鏈接是_entry.articleURL。短短几分鐘後,iPhone終止連接,最終我只下載了一小部分mp3。任何想法可能造成這種情況?NSURL iPhone應用程序的連接下載在完成之前終止

-(void)didSelectRowAtIndexPath 
{  RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row]; 

      self.nameit = entry.articleTitle; 
      NSURL *url = [NSURL URLWithString:entry.articleUrl];  
      NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; 
      __block NSURLConnection *connection = [NSURLConnection connectionWithRequest:theRequest delegate:self]; 

      UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance 

      __block UIBackgroundTaskIdentifier background_task; //Create a task object 

      background_task = [application beginBackgroundTaskWithExpirationHandler:^{ 
       // This code gets called when your app has been running in the background too long and the OS decides to kill it 
       // You might want to cancel your connection in this case, that way you won't receive delegate methods any longer. 
       [connection cancel]; 
       [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks 
       background_task = UIBackgroundTaskInvalid; //Set the task to be invalid 

       //System will be shutting down the app at any point in time now 
      }]; 

      self.backgroundTaskIdentifier = background_task; 
      if (connection) { 
       receivedData = [[NSMutableData data] retain]; 
       self.thetable = tableView; 
       self.thepath = indexPath; 
      } 
      else { 
       UIAlertView *cancelled = [[UIAlertView alloc] initWithTitle:@"Download Failed" message:@"Please check your network settings, and then retry the download." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
       [cancelled show]; 
       [cancelled release]; 
      } 
} 

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
progress.hidden = NO; 
downloadInProgress = YES; 
RSSEntry *entry = [_allEntries objectAtIndex:thepath.row]; 

self.nameit = entry.articleTitle; 
downloadlabel.text = [NSString stringWithFormat:@"%@", nameit]; 
[thebar addSubview:downloadlabel]; 
[receivedData setLength:0]; 
expectedBytes = [response expectedContentLength]; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
[receivedData appendData:data]; 
float progressive = (float)[receivedData length]/(float)expectedBytes; 
[progress setProgress:progressive]; 


} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
[connection release]; 
UIAlertView *connectionfailed = [[UIAlertView alloc] initWithTitle:@"Download Failed" message:@"Please check your network settings, and then retry the download." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
[connectionfailed show]; 
[connectionfailed release]; 
progress.hidden = YES; 
downloadInProgress = NO; 
[downloadlabel removeFromSuperview]; 
[thetable deselectRowAtIndexPath:thepath animated:YES]; 
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier]; 
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; 
[connection release]; 



} 

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { 
return nil; 
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection { 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[nameit stringByAppendingString:@".mp3"]]; 
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); 
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
[receivedData writeToFile:pdfPath atomically:YES]; 
progress.hidden = YES; 
downloadInProgress = NO; 
[downloadlabel removeFromSuperview]; 

[thetable deselectRowAtIndexPath:thepath animated:YES]; 

[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier]; 
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; 
} 

問題是,似乎connectionDidFinishLoading一直在調用,即使不完整。有什麼想法嗎?

回答

1

不確定爲什麼你使用beginBackgroundTaskWithExpirationHandler來完成這項工作 - 它的目的是完成一個完全不同的任務(在你的應用程序移動到後臺後做一些工作,在前臺使用這個工作很可能你做你的問題的原因。

我所說的其實是走在github等打交道了一個樣本並行的NSOperation示範項目,並使用它們做你的異步NSURLConnections。

此外,要更新GUI請注意,您必須在主線程上使用UIKit,如果您需要更新某些內容,只需使用一個塊並將其分派到主隊列中進行更新。

+0

我有這個在那裏,即使在後臺下載可以繼續下去。 – user717452 2012-07-18 02:08:58

+0

我廣泛使用塊和並行NSOperations。 github上的所有示例項目都差不多,我對如何獲得runloop和autorelease池設置進行了廣泛的評論,但是無論如何,你寫的內容在我的經驗中是非常不尋常的,儘管你可能會得到它最終會工作,因爲我懷疑其他人是否能夠把它全部弄清楚。 – 2012-07-18 13:59:01

相關問題