objective-c - ASIHttp 同步请求在返回后运行委托(delegate)方法

标签 objective-c download asihttprequest

我正在尝试从服务器下载文件。我的代码如下。在 didFinishLaunchingWithOptions 方法中,我使用运行以下代码的 detachNewThreadSelector 创建了一个新线程。

NSString *destPath = [self.home_dir_path stringByAppendingPathComponent:[NSString stringWithFormat:@"_%@",content_data_file_name]];
[ContentBO downloadFile:destPath  content_name:content_data_file_name];
if([self updatesAvailable]){
    //update content
}else{
    //launch app
}

我的下载文件代码是:

@try{
    NSString *url = [NSString stringWithFormat:@"%@/%@",ServerURL,content_name];
    NSLog(@"downloading URL is: %@",url);
    self.request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
    [self.request setRequestMethod:@"GET"];
    [self.request setDownloadDestinationPath:destFilePath]; 
    NSLog(@"destination path is: %@",destFilePath);
    [self.request setTimeOutSeconds:30];

    [self.request setDelegate:self];
    [self.request startSynchronous];

    NSError *error = [self.request error];
    NSData *receivedData = nil;

    if (!error) {
        isSuccess = YES;
        self.responseStr = [request responseString];
        receivedData = [NSData dataWithData:[self.request responseData]];
    }
    else {
        isSuccess = NO;
        NSLog(@"The following error occurred: %@", error);
    }
}@catch(NSException *e){
    NSLog(@"exception occured.");
}

我对同步调用的理解是这是一个阻塞调用,控制不应该低于

[ContentBO downloadFile:destPath  content_name:content_data_file_name];

直到控制超出 ASIHTTPRequestDelegate 的 requestFinished 方法。在我的例子中,发生的事情是控件同时执行 requestFinished 和下面的代码

[ContentBO downloadFile:destPath  content_name:content_data_file_name];

但我不希望控件在从 requestFinished 方法出来之前低于 [ContentBO downloadFile...]。

最佳答案

requestFinished 委托(delegate)调用在主线程上异步运行,而您的代码不在主线程上运行,因此预计两者会同时运行。

但是,由于您使用的是同步请求,为什么不删除 requestFinished 的内容并将代码放在“startSyncronous”行之后?当 startSynchronous 返回时,您可以保证请求已完成。

关于objective-c - ASIHttp 同步请求在返回后运行委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6278875/

相关文章:

ios/xcode/objective-c : Any way to link to other view controller in core-data driven page?

java - 应用程序未下载最新版本的文件 [Java]

objective-c - ASIHTTPRequest 似乎总是缓存 JSON 数据

iphone - ASIHTTPRequest 下载缓存问题 - 无法在缓存中保存/加载日期

iphone - AFNetworking - 下载多个文件 + 通过 UIProgressView 监控

iOS 9.2 UIDatePicker组件当前选中组件行的文本颜色没有改变

objective-c - NSDateFormatter 正在移动 2 小时的日期,为什么?

ios - Xcode 6.0 中头文件被错误更改并卡在模拟器上运行

r - Shiny:下载表格数据和绘图

linux - 如何在后台运行 wget 以进行无人值守的文件下载?