2010-06-30 73 views
2

我之前通過使用dataWithContentsOfURL下載了一個jpg然後writeToFile來保存它,從而爲我的應用下載圖像。Iphone JPEG數據流不包含使用NSURLConnection的圖像

我最近; Y開始使用NSURLConnetion做相同的,但現在我得到follwoing錯誤和崩潰:

腐敗JPEG數據:87個多餘字節 JPEG數據流內沒有圖像

我知道這些圖像不是corrumpt,因爲應用程序正在使用以前的方法正常下載它們。這裏是我的代碼:

-(void) downloadSave { 

    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; 

    NSString *tempString = [[NSString alloc]initWithFormat:@"http://www.mysite.com/%@.jpg",chartFileName]; 
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:tempString] 
               cachePolicy:NSURLRequestUseProtocolCachePolicy 
              timeoutInterval:10.0]; 
    // create the connection with the request 
    // and start loading the data 

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    if (theConnection) { 
     // Create the NSMutableData to hold the received data. 
     // receivedData is an instance variable declared elsewhere. 
     mutableData = [[NSMutableData data] retain]; 
     self.image = nil; 
     NSLog(@"connection exists"); 
     [NSURLConnection connectionWithRequest:theRequest delegate:self]; 

    } else { 
     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error" message:@"There was an error contacting the chart servers. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alert show]; 
     [alert release]; 
     [activityIndicator stopAnimating]; 


    } 




// NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
//              NSUserDomainMask, YES); 

// NSString *docsPath = [paths objectAtIndex:0]; 
// NSString *downloadPath = [[[NSString alloc]initWithFormat:@"http://www.mysite.com/%@.jpg",chartFileName]autorelease]; 
// downloadedChartData = nil; 


    [pool drain]; 
    [pool release]; 




} 


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    // 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. 
    NSLog(@"got to connection did receive response"); 
    [mutableData setLength:0]; 
} 




- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    // Append the new data to receivedData. 
    // receivedData is an instance variable declared elsewhere. 
    [mutableData appendData:data]; 
// NSLog(@"got some data, total: %i",mutableData.length); 
} 


- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error 
{ 
    // release the connection, and the data object 
// [connection release]; 
    // receivedData is declared as a method instance elsewhere 
    // self.mutableData = nil; 

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


- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // do something with the data 
    // receivedData is declared as a method instance elsewhere 
    NSLog(@"Succeeded! Received %d bytes of data",[mutableData length]); 
    [connection release]; 
    // release the connection, and the data object 
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                 NSUserDomainMask, YES); 
    NSString *docsPath = [paths objectAtIndex:0]; 
    self.image = nil; 

    NSString *savePath = [[[NSString alloc]initWithFormat:@"%@/%@.jpg",docsPath, chartFileName]autorelease]; 

    [mutableData writeToFile:savePath atomically:YES]; 
    self.mutableData = nil; 
+0

只是一個更新 - 當我通過查找器檢查文檔文件夾以查看我已下載的圖像時,看起來它們實際上已損壞。爲什麼使用NSURLConnection會導致它們被破壞? – Brodie 2010-06-30 06:50:00

+1

你看過下載的「圖像」了嗎?在文本編輯器中打開它,看看裏面有什麼......也許你的問題是其他的東西,比如404錯誤頁面等。另外,還有stringByAppendingPathComponents:它更適合路徑擴展。 – Eiko 2010-07-02 20:04:17

+0

您應該接受Tonclon的回答,或者讓我們知道它是否不正確。它看起來很適合我。 – 2010-07-07 15:01:14

回答

8

要初始化並啓動 NSURLConnections具有相同的委託。由於您的委託方法不檢查哪個連接稱爲它們,所以在一個NSMutableData實例中將圖像的兩倍字節混合在一起。

// Creates, initializes and starts an instance of NSURLConnection  
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
... 
// Creates, initializes and starts another instance of NSURLConnection, with same request and delegate 
[NSURLConnection connectionWithRequest:theRequest delegate:self]; 

在相同的代表實例,這意味着它們的數據相同的實現方式被寫入到同一NSMutableData以隨機順序這兩個連接消息。

我建議乾脆擺脫線:

[NSURLConnection connectionWithRequest:theRequest delegate:self]; 

另一件事:爲什麼你downloadSave使用一個自動釋放池?如果你從主線程調用它,你只有一個NSURLRequest在該池中自動釋放。如果從另一個線程調用它,則必須注意,該線程的runloop已設置並正在運行,否則根本不會收到任何委託回調。