为什么没有互联网连接AFNetworking成功运作?

时间:2015-08-15 12:10:21

标签: ios afnetworking internet-connection

当我第一次完成此代码而没有互联网连接时,它会显示警告应该如何进行。但是,当我首先成功完成互联网连接,然后关闭互联网连接时,所有下一次执行都将成功完成相同的响应对象。没有在设备上试过,只有iOS模拟器。

NSString *string = @"https://money.yandex.ru/api/categories-list";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    [self deleteAllObjects];
    self.numberOfBranchObjects = 0;
    for (NSString *key in (NSDictionary *)responseObject) {
        [self insertNewObject:key fromSender:self];
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                        message:[error localizedDescription]
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
    [alertView show];
}];
[operation start];

AFNetworking是否有任何缓存用于响应对象或其他?

1 个答案:

答案 0 :(得分:0)

是的,它确实缓存了,你走了:

[operpation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
    return nil;
}];

我建议您在请求之前直接测试互联网连接。

你可以把它放在视图控制器的初始化部分:

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

然后在之前调用此方法:

- (BOOL)connected {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}