ios - AFNetworking 故障 block

标签 ios afnetworking-2

我正在使用 afnetworking 2.0 来显示 youtube 视频。 当我遇到连接错误时,我会打开一个警报 View ,如果我单击“确定”,我想停止请求。

警报 View 显示正确,但当我单击“确定”时,请求没有停止并且我看到了事件指示器。

如何停止请求?

这是下面的代码:

-(void)loadData {

NSString *urlAsString = @"https://gdata.youtube.com/feeds/api/videos?q=wankel&v=2&max-results=50&alt=jsonc";

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] init];
activityIndicator.color = [UIColor blackColor];
activityIndicator.backgroundColor = [UIColor blackColor];
[activityIndicator startAnimating];
[self.view addSubview:activityIndicator];
activityIndicator.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 );

NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    self.moviesArray = [responseObject valueForKeyPath:@"data.items"];
    NSLog(@"%@", moviesArray);

    self.thumbnailsArray = [responseObject valueForKeyPath:@"data.items.thumbnail"];

    self.moviesDetailArray = [responseObject valueForKeyPath:@"data.items"];

    [activityIndicator setHidden:YES];
    [activityIndicator stopAnimating];


    [self.collectionView reloadData];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    UIAlertView *alertView =[[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@", error.localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Try again", nil];
    [activityIndicator setHidden:YES];
    [activityIndicator stopAnimating];      
    [alertView show];           
    }];

[operation start];
}

最佳答案

您是否尝试过将操作添加到 AFHTTPRequestOperationManager ? 管理器有一个 operationQueue 属性。您可以从那里取消操作。

当操作失败时,从共享管理器中停止操作。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.operationQueue cancelAllOperations];

编辑: 如果您正在寻找特定的操作,您可以遍历队列中的操作:

for (NSOperation *operation in manager.operationQueue.operations) {
    // check if this is the right operation, and cancel it.
}

关于ios - AFNetworking 故障 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22208226/

相关文章:

ios - Appium NSPredicate 从子查询中选择单个项目

ios - Jenkins 是否支持 Xcode 集成

ios - AFURLSessionManager downloadTaskWithRequest 立即取消

iOS 应用程序在调用 Web 服务最佳实践之前确保互联网可用

ios - 如何从另一个 ViewController (Swift) 访问 UITextField 中的文本?

ios - MKMapView 无限水平滚动

ios - 如何准确检测设备型号?

ios - 在 AFNetworking 故障 block 中弹出 UINavigationController

php - 使用 AfNetworking 2 将数据发布到 PHP 时,带有 NSArray 的 NSDictionary 正在转换为元素数组

ios - AFNetworking 2.0 中的 setImageWithURL