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");
}
4

1 回答 1

0

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

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

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

于 2013-07-15T05:33:25.377 回答