objective-c - AFNetworking:为更高优先级的请求中断后台请求

标签 objective-c ios5 grand-central-dispatch nsoperationqueue afnetworking

使用 AFNetworking,我需要在后台下载约 100 张图像并将它们存储到磁盘,同时确保我的应用程序中的任何其他网络连接优先。

~~~~~~~

我有一个有 4 个选项卡的应用程序。每个选项卡基本上做同样的事情:从服务器拉下 JSON 响应,并显示图像的缩略图网格,按需拉下每个图像(使用 AF 的 ImageView 类别)。点击缩略图会将您带到详细 View Controller ,您可以在其中看到更大的图像。每个选项卡的响应和图像都不同。

新的要求是提前获取第 4 个选项卡的所有图像,因此理论上当用户点击第 4 个选项卡时,JSON 数据和图像将从磁盘中读取。

我现在或多或少已经开始工作了,第 4 个选项卡预取并保存到磁盘是在后台线程上执行的,因此主线程不会锁定。但是,当用户在第一个、第二个或第三个选项卡上时启动的网络请求被预取网络请求阻止。

我正在使用 AFNetworking,这是我在加载选项卡 1、2 或 3 时使用的代码:

// this network request ends up getting blocked by the network request that
// is fired upon the application becoming active
- (void)getAllObjectDataWithBlock:(AFCompletionBlockWrapper)block
{
    [[[MyAPIClient] sharedClient] getPath:@"" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        block(operation, responseObject, nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        block(operation, nil, error);
    }];
}

下面是我在应用程序激活时使用的代码,用于为第 4 个选项卡预取内容:

// this network request runs in the background, but still blocks requests
// that should have a higher priority
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSOperationQueue *imageQueue = [[NSOperationQueue alloc] init];
        [imageQueue setMaxConcurrentOperationCount:8];

        for (NSString *imageURL in self.images) {                    
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL imageURL]];

            AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request];
            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"success");
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"fail");
            }];

            [imageQueue addOperation:smallOperation];
        }
    });
}

我如何构造事物以便从主线程启动的任何网络请求中断在后台线程启动的网络请求?

最佳答案

我不知道您是否可以轻松中断正在运行的操作,除非您想向它们发送 cancel——但您必须查看是否 AFImageRequestOperation注意 isCancelled

您是否尝试过使用 setQueuePriority ?您可以以低优先级开始所有预取请求,然后添加具有更高优先级的当前选项卡请求。我相信正在运行的操作会完成,但一旦它们完成,您的高优先级操作将排在排队的低优先级操作之前。

关于objective-c - AFNetworking:为更高优先级的请求中断后台请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12188131/

相关文章:

ios - 如果我想让一个任务在后台运行, "dispatch_get_global_queue"队列如何工作?

iphone - 异步进程给我带来了麻烦

ios - SpriteKit SKEmitternode Targetnode 修改整个Node

ios - 每隔一段时间播放一次UILocalNotification声音

iphone - 不使用baseURL我们可以在UIWebView中添加本 map 片吗

iphone - iOS 5 实例变量

iphone - GLKTextureLoader 第一次加载某个纹理失败,但第二次成功

iphone - 当我的手指移动时如何填充图像的透明区域

objective-c - 停止自动调用 ios5 生命周期事件

ios - 有没有办法实现dispatch_cancel()?