为什么 AFNetworking 在没有互联网连接的情况下也能成功运行?
Why AFNetworking successfully works without 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 是否有用于响应对象的缓存或其他内容?
是的,它确实有缓存,给你:
[operpation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
return nil;
}];
不过,我建议您在请求之前直接测试互联网连接。
您可以通过将其放入视图控制器的初始化部分来实现:
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
那么之前调用这个方法即可:
- (BOOL)connected {
return [AFNetworkReachabilityManager sharedManager].reachable;
}
当我第一次在没有互联网连接的情况下完成此代码时,它会显示警报应该如何进行。但是当我首先通过互联网连接成功完成它然后关闭互联网连接时,所有下一次执行都将使用相同的响应对象成功完成。还没有在设备上试过,只有 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 是否有用于响应对象的缓存或其他内容?
是的,它确实有缓存,给你:
[operpation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
return nil;
}];
不过,我建议您在请求之前直接测试互联网连接。
您可以通过将其放入视图控制器的初始化部分来实现:
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
那么之前调用这个方法即可:
- (BOOL)connected {
return [AFNetworkReachabilityManager sharedManager].reachable;
}