2013-07-14 103 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對象所附着的運行循環。默認情況下,它會使用當前線程的運行循環,所以你應該NSURLDownload對象的初始化之後做這樣的事情:

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

屬性self.downloaded和self.error應該在回調進行設置。
主線程運行循環可能由NSApplication對象啓動。

相關問題