我试图弄清楚如何使用 AFNetworking 2 和可达性显示“无互联网连接”警报。
我将 Reachability 和 AFNetworking 导入到我的控制器中。我从 AFNetworking 2 文档中复制的代码部分开始,AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
我不确定它是否属于它。
更新
我的应用程序现在会在没有互联网连接时显示警报,但是警报显示需要很长时间,我也怀疑这是我构建代码的最佳方式。(另外,如果我在主视图控制器上,并且在没有连接时单击一个单元格,应用程序崩溃,我不知道是否有办法解决这个问题)。
- (void)viewDidLoad
{
[super viewDidLoad];
Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];
reach.reachableBlock = ^(Reachability * reachability)
{
NSLog(@"Reachable");
};
reach.unreachableBlock = ^(Reachability * reachability)
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"No internet connection"
message:@"No internet connection"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
NSLog(@"Not Reachable");
};
[reach startNotifier];
self.upcomingReleases = [[NSMutableArray alloc] init];
[self makeReleasesRequests];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; // Make nav items white
[self.collectionView registerClass:[ReleaseCell class] forCellWithReuseIdentifier:@"ReleaseCell"];
}
-(void)makeReleasesRequests
{
NSURL *url = [NSURL URLWithString:@"http://www.soleresource.com/upcoming.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"@");
self.upcomingReleases = [responseObject objectForKey:@"upcoming_releases"];
[self.collectionView reloadData];
} failure:nil];
[operation start];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended:NO];
break;
case AFNetworkReachabilityStatusNotReachable:
default:
[operationQueue setSuspended:YES];
break;
}
}];
}
谢谢。