2010-06-29 3 views
1

내 응용 프로그램에서 작동하도록 NSURLConnection을 얻으려고합니다. 나는 애플의 코드를 거의 정확히 따라 왔지만 작동하지 않는 것 같다. NSURLConnection은 downloadSave라는 메서드 안에 있습니다. 이 메서드는 끝까지 제대로 실행되며 내 로그는 "연결이 있음"을 나타냅니다. 그러나 대리자 메서드가 호출되지 않는 것처럼 아무 것도 발생하지 않습니다.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 

} 

로그에 나타나는 유일한 것은입니다 : 당신이 NSAutoReleasePool (말을하지 그게 전부 가지고

+0

릴리스 풀을 사용함에 따라 별도의 스레드에서 NSURLConnection을 호출하고 있습니까? 외모에 의해 당신은 NSURLConnection 자식 스레드에서 만드는 있지만 대리자 메서드를 주 스레드에서 내가 생각하지 않는 작업 – Rudiger

답변

3

난 단지 downloadSave 별도의 스레드에서 호출에 코드로 추측 할 수있다 "연결이 존재합니다"무엇을 당신의하고 있지만 가능성). NSURLConnection은 주 스레드에서 초기화 될 때 주 스레드의 대리자 메서드에만 응답 할 수 있습니다.

NSURLConnection은 이미 스레드 위임 호출이므로 스레드로 작성하지 않아도됩니다. 어떤 이유로 든 스레드해야 할 경우 사용할 수 있어야합니다.

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

그러면 데이터를 하위 스레드로 반환해야합니다.

관련 문제