2013-07-14 1 views
0

저는 코코아 프로그래밍에 익숙하지 않습니다. URL에서 디스크로 다운로드하려고합니다. 불행히도 메서드는 어떤 이유로 콜백되지 않습니다. downloadFile에 대한 호출은 [self performSelectorOnBackground] 등을 통해 시작된 백그라운드 스레드에서 이루어집니다. 어떤 아이디어가 잘못 되었습니까?코코아 다운로드 파일 콜백이 백그라운드 스레드에서 다운로드 할 때 호출되지 않습니다. 메인 스레드에서 작동합니다.

참고 주 UI 스레드에서 downloadFile을 호출하면 작동하는 것처럼 보이지만 배경 스레드는 무엇입니까?

-(BOOL) downloadFile 
{ 
     BOOL downloadStarted = NO; 
     // Create the request. 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:versionLocation] 
       cachePolicy:NSURLRequestUseProtocolCachePolicy 
       timeoutInterval:60.0]; 

    // Create the connection with the request and start loading the data. 
     NSURLDownload *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest 
                                   delegate:self]; 
    if (theDownload) { 
     // Set the destination file. 
     [theDownload setDestination:@"/tmp" allowOverwrite:YES]; 
       downloadStarted = YES; 
    } else { 
     // inform the user that the download failed. 
       downloadStarted = NO; 
    } 

     return downloadStarted; 

} 


- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error 
{ 
    // Release the connection. 
    [download release]; 

    // Inform the user. 
    NSLog(@"Download failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 

- (void)downloadDidFinish:(NSURLDownload *)download 
{ 
    // Release the connection. 
    [download release]; 

    // Do something with the data. 
    NSLog(@"%@",@"downloadDidFinish"); 
} 

답변

0

나는 당신이 당신의 NSURLDownload 객체가 부착 된 실행 루프를 시작한다고 생각합니다.

NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; 
while (!self.downloaded && !self.error && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) 
     ; 

속성 self.downloaded 및 self.error이 당신의 콜백에 설정해야합니다 : 당신은 아마 NSURLDownload 객체의 초기화 후에 이런 일을해야하므로 기본적으로는, 현재의 thread의 실행 루프를 사용합니다.
주 스레드에서 루프는 NSApplication 개체에 의해 시작되었습니다.

관련 문제