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
}
出現在日誌中唯一的一點是:「存在連接」
由於您正在使用發佈池,您是否在單獨的線程中調用NSURLConnection?通過它的外觀,你在子線程中創建NSURLConnection,但是你的委託方法在主線程中,我認爲它不工作 – Rudiger 2010-06-29 01:27:03