IOS - 总结(网络状态变更)

时间:2023-02-12 12:49:01

- (void)initNetworkMonitor

{

    NSURL *baseURL = [NSURL URLWithString:@"http://www.baidu.com/"];

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

    NSOperationQueue *operationQueue = manager.operationQueue;

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

        static AFNetworkReachabilityStatus lastStatus = 2;

        switch (status) {

            case AFNetworkReachabilityStatusReachableViaWWAN:

            case AFNetworkReachabilityStatusReachableViaWiFi:

                [operationQueue setSuspended:NO];

                if (lastStatus == -1 || lastStatus == 0) {

                    [self showAlertTitle:@"提醒:" message:@"当前网络已连接,网络状态良好!"];

                }

                break;

            case AFNetworkReachabilityStatusNotReachable:

            default:

                [operationQueue setSuspended:YES];

                if (lastStatus == 1 || lastStatus == 2) {

                    [self showAlertTitle:@"提醒:" message:@"当前网络不可用,请请稍后重试!"];

                }

                break;

        }

        lastStatus = status;

    }];

}