ios – 当设备离线时使用setReachabilityStatusChangeBlock什么也不做,AFNetworking 2.0队列请求

前端之家收集整理的这篇文章主要介绍了ios – 当设备离线时使用setReachabilityStatusChangeBlock什么也不做,AFNetworking 2.0队列请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当设备脱机时,我一直在尝试使用AFNetworking来排列HTTP请求的解决方案,所以当它返回在线时,请求完成.据我所了解,这可以设置setReachabilityStatusChangeBlock:参数.

到目前为止,这是我所拥有的:

// ViewController.h
@interface XYZTicketViewController : UIViewController<NSURLConnectionDelegate> // This is from before I started using AFNetworking,I'm intending to change all the requests to use AFNetworking in the near future.   
@end 


// ViewController.m
(...)
#import <AFHTTPRequestOperationManager.h>
#import <AFNetworkReachabilityManager.h>
(...)
@interface XYZTicketViewController ()
- (void)viewDidLoad
(...)
{
NSURL *baseURL = [NSURL URLWithString:@"http://54.213.167.202"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue setSuspended:NO];
            NSLog(@"WIFI");
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            [operationQueue setSuspended:YES];
            NSLog(@"oflline,baby");
            break;
    }
}];

NSDictionary *parameters = @{@"action": @"login",@"user": @"mail.address@gmail.com",@"pass": @"howdoyouturnthison"};
[manager GET:@"http://54.213.167.202/api.PHP"  parameters:parameters success:^(AFHTTPRequestOperation *operation,id responSEObject) {
    NSLog(@"JSON: %@",responSEObject);
} failure:^(AFHTTPRequestOperation *operation,NSError *error) {
    NSLog(@"Error: %@",error);
}];
(...)
}

我找不到任何例子,但我读了here这是可能的,但到目前为止,当在线状态发生变化时,任何事情都会发生.

希望你能帮助我

解决方法

调用setReachabilityStatusChangeBlock之前,需要调用startMonitoring

[manager.reachabilityManager startMonitoring];

如果您使用的是AFNetworking 2.0,我建议如下:

[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    DLog(@"Reachability: %@",AFStringFromNetworkReachabilityStatus(status));
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue setSuspended:NO];
            NSLog(@"WIFI");
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            [operationQueue setSuspended:YES];
            NSLog(@"offline,baby");
            break;
    }
}];
原文链接:https://www.f2er.com/iOS/330410.html

猜你在找的iOS相关文章