从后台线程下载时未调用的cocoa下载文件回调,适用于主线程

时间:2013-07-14 10:41:20

标签: macos cocoa

我是cocoa编程的新手,我正在尝试将二进制文件从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");
}

1 个答案:

答案 0 :(得分:0)

我认为您应该启动NSURLDownload对象所附加的运行循环。默认情况下,它将使用当前线程的运行循环,所以你可能应该在初始化NSURLDownload对象后做这样的事情:

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

应在回调中设置属性self.downloaded和self.error 在主线程运行循环中,可能由NSApplication对象启动。