2010-06-29 72 views
1

我試圖讓NSURLConnection在我的應用程序中工作。我幾乎完全按照蘋果的代碼,但它似乎並沒有工作。 NSURLConnection位於名爲downloadSave的方法內部。這個方法在最後運行正常,而且我的日誌指出「Connection Exists」 - 但是之後沒有任何反應,就好像沒有任何委託方法被調用一樣。iPhone NSURLConnection - 代表不工作

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

    NSString *tempString = [[NSString alloc]initWithFormat:@"http://www.myWebsite.com/%@.jpg",chartFileName]; 
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:tempString] 
               cachePolicy:NSURLRequestUseProtocolCachePolicy 
              timeoutInterval:10.0]; 


    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    if (theConnection) { 


     mutableData = [[NSMutableData data] retain]; 
     self.image = nil; 
     NSLog(@"connection exists"); 


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


    } 

    [pool drain]; 
    [pool release]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 

    NSLog(@"got to connection did receive response"); 
    [mutableData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 

    [mutableData appendData:data]; 
    NSLog(@"got some data were at %i",mutableData.length); 
} 


- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error 
{ 

    [connection release]; 
    // receivedData is declared as a method instance elsewhere 
    self.mutableData = nil; 

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


- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 

    NSLog(@"Succeeded! Received %d bytes of data",[mutableData length]); 

//more code follows to display the downloaded image 

} 

出現在日誌中唯一的一點是:「存在連接」

+0

由於您正在使用發佈池,您是否在單獨的線程中調用NSURLConnection?通過它的外觀,你在子線程中創建NSURLConnection,但是你的委託方法在主線程中,我認爲它不工作 – Rudiger 2010-06-29 01:27:03

回答

3

因爲你有一個NSAutoReleasePool(不是說這就是我只能給你的代碼downloadSave在調用一個單獨的線程猜測你的行爲,但可能)。當NSURLConnection在主線程中初始化時,它只能響應主線程中的委託方法。

由於NSURLConnection已經是線程委託調用,您不需要在線程中創建它。如果你需要線程出於某種原因,你應該能夠使用

NSError *error; 
NSURLResponse *response; 
NSData *connectionData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error]; 

而且應該返回數據到子線程。