2011-11-19 39 views
-1

在我的應用程序即時通訊使用NSURLConnection下載一些視頻。它顯示兩條內存警告。下載視頻時應用程序崩潰

  Received memory warning. Level=1 
      Received memory warning. Level=2 

然後在某些時候應用程序崩潰有什麼辦法來解決這個問題。 任何人都可以幫助我解決這個問題。

在此先感謝。我用

代碼:

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:[exer1 objectAtIndex:i-1]]cachePolicy:NSURLRequestUseProtocolCachePolicy 
               timeoutInterval:60.0]; 
    NSLog(@"%@ urlrequest ",theRequest); 


     NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 

     HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain]; 

     HUD.labelText =[NSString stringWithFormat:@"Downloading %d Video",[exer1 count]-(i-1)]; 

     if (theConnection) { 
      // Create the NSMutableData to hold the received data. 
      // receivedData is an instance variable declared elsewhere. 
      receivedData = [[NSMutableData data] retain]; 

     } else { 
      // Inform the user that the connection failed. 
     } 

     } 

    } 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    expectedLength = [response expectedContentLength]; 
    currentLength = 0; 
    HUD.mode = MBProgressHUDModeDeterminate; 

    NSLog(@"%d expectedLength",expectedLength); 

    // This method is called when the server has determined that it 
    // has enough information to create the NSURLResponse. 

    // It can be called multiple times, for example in the case of a 
    // redirect, so each time we reset the data. 

    // receivedData is an instance variable declared elsewhere. 
    [receivedData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    currentLength += [data length]; 
    HUD.progress = currentLength/(float)expectedLength; 
    // Append the new data to receivedData. 
    // receivedData is an instance variable declared elsewhere. 
    [receivedData appendData:data]; 

} 

- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error 
{ 
    [HUD hide:YES]; 
    // release the connection, and the data object 
    // [connection release]; 
    // receivedData is declared as a method instance elsewhere 
    // [receivedData release]; 

    // inform the user 
    NSLog(@"Connection failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 

    if(tempz == 1){ 

     tempz =0; 
     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"The Internet connection appears to be offline." message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil]; 
     [alert show]; 
     [alert release]; 
    } 



} 


- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSError *err; 
    NSFileManager *fman = [NSFileManager defaultManager]; 

    NSString *path = [[[fman URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path]; 
    NSDictionary *fattr = [fman attributesOfFileSystemForPath:path error:&err]; 
    //Error checking 
    NSUInteger freeSize = [[fattr objectForKey:NSFileSystemFreeSize] unsignedIntegerValue]; 

    NSLog(@"Free Space %d", freeSize); 

    NSArray* paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    struct statfs tStats; 
    statfs([[paths1 lastObject] cString], &tStats); 
    float total_space = (float)(tStats.f_blocks * tStats.f_bsize); 


    NSLog(@"%f total_space",total_space); 



     [SavedVid addObject:[exer1 objectAtIndex:i-1]]; 
     NSUserDefaults *currentDefaults6 = [NSUserDefaults standardUserDefaults]; 
     [currentDefaults6 setObject:[NSKeyedArchiver archivedDataWithRootObject:SavedVid] forKey:@"SavedVid"]; 
     [currentDefaults6 synchronize]; 


     NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] ; 


    /* NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 


    NSLog(@"%@ documentsDirectory",documentsDirectory); 
    if (!documentsDirectory) { 
     NSLog(@"Documents directory not found!"); 
    } 

    */ 


    NSString *file2 = [NSString stringWithFormat:@"%@/%@.mp4",cacheDirectory,[elementw.description objectAtIndex:i-1]]; 


    /* NSLog(@"%@ documentsDirectory",file2); 
     NSLog(@"%@ ---- i elementw.description ---- %d ",elementw.description,i); 
    */ 
    [receivedData writeToFile:file2 atomically:YES]; 

    NSLog(@" %@ file 2 ",file2); 

    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tick.png"]] autorelease]; 
    HUD.mode = MBProgressHUDModeCustomView; 
    [HUD hide:YES afterDelay:2]; 


    [self initializPlayer]; 

    // release the connection, and the data object 
    // [connection release]; 
// [receivedData release]; 
} 
+1

請告訴我們您的代碼下載的視頻,否則我們不知道究竟發生什麼事。 – sosborn

+0

@sosborn我編輯了我的代碼,請你檢查 – ishhhh

回答

0

我覺得你保持視頻在你的記憶。根據大小它可能會導致內存問題。

1

當收到數據時,您需要將其存儲在臨時(或非臨時)文件中。問題是整個文件正在下載到內存,這將消耗大部分內存。

應用程序崩潰,因爲它使用的內存太多,所以寫入文件是最佳選擇。

事情是這樣的:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    currentLength += [data length]; 
    HUD.progress = currentLength/(float)expectedLength; 

    NSString *temporaryFile = [NSString stringWithFormat:@"%@/fileDownload.part", NSTemporaryDirectory()]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:temporaryFile]) { 
     [[NSFileManager defaultManager] createFileAtPath:temporaryFile contents:nil attributes:nil]; 
    } 

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:temporaryFile]; 
    [fileHandle seekToEndOfFile]; 
    [fileHandle writeData:data]; 
    [fileHandle closeFile]; 

    if (currentLength == expectedLength) { 
     //read from the file stored at temporaryFile 
     //perhaps move to a permanent location and change 
     //its file name and extension. 
    } 

} 
+0

當我把這段代碼放到App中後,下載永遠不會結束。它只是卡在那裏。 – ishhhh

+0

嘗試刪除if語句...它應該工作然後.. –

+0

我不知道,但我仍然面臨同樣的問題。並在很多時間後下一個視頻下載。我需要做這個代碼中的其他任何東西? – ishhhh

相關問題