ios 使用 AFNetworking 2.0 设置可达性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20035917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:24:32  来源:igfitidea点击:

Setting up reachability with AFNetworking 2.0

iosios6afnetworkingreachabilityafnetworking-2

提问by StuartM

I am trying to setup Reachability using the new 2.0 AFNetworking.

我正在尝试使用新的 2.0 AFNetworking设置可达性。

In my AppDelegate I initialise the sharedManager.

在我的 AppDelegate 中,我初始化了 sharedManager。

// Instantiate Shared Manager
[AFNetworkReachabilityManager sharedManager];

Then in the relevant VC method I check to see if isReachable:

然后在相关的 VC 方法中我检查是否 isReachable:

// Double check with logging
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
    NSLog(@"IS REACHABILE");
} else {
    NSLog(@"NOT REACHABLE");
}

At present this is not working as expected in the simulator, but I imagine this would need to be tested on device and not simulator.

目前这在模拟器中没有按预期工作,但我想这需要在设备上而不是模拟器上进行测试。

QuestionWhat I would like to do is monitor the connectivity within the VC. So I run the following in the viewDidLoad:

问题我想做的是监控 VC 内的连接。所以我在 viewDidLoad 中运行以下命令:

// Start monitoring the internet connection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];

How would I then register for the changes? What is/would be called once the network connection changes I cannot see this from the documentation.

我将如何注册更改?一旦网络连接发生变化,什么是/将被调用我从文档中看不到这一点。

回答by Gabriele Petronella

As you can read in the AFNetworking read me page

正如您在AFNetworking 的自述页面中所读到的那样

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

Here's also a link to the official documentation.

这里也是官方文档的链接

回答by Marlon Ruiz

I have a singleton AFHTTPRequestOperationManager class. In the singleton has a method:

我有一个单例 AFHTTPRequestOperationManager 类。在单例中有一个方法:

+(void)connectedCompletionBlock:(void(^)(BOOL connected))block {

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

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

    BOOL con = NO;
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

    if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {

        con = YES;
    }

    if (block) {
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
        block(con);
    }

}];

}

}

Before make a request you call this method that return a block indicating if internet is reachable:

在发出请求之前,您调用此方法返回一个块,指示是否可以访问互联网:

[TLPRequestManager connectedCompletionBlock:^(BOOL connected) {
    if (connected) {

       // Make a request

    }else{

        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Notice" message:@"Internet is not available." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];

        [alertView show];

    }

}];

回答by onCompletion

I was just going through your question and all the answers. After that I decided to do all these things once. So, in my existing project I just included the AFNetworking through cocoa-pods and here is the solution which is woking for me completely.

我只是在浏览你的问题和所有答案。之后,我决定将所有这些事情都做一次。所以,在我现有的项目中,我只是通过 cocoa-pods 包含了 AFNetworking,这是完全适合我的解决方案。

Solution -- First of all AFNetworkReachabilityManager is a singleton class. You don't need to do AppDelegate initialisation for sharedManager.

解决方案——首先,AFNetworkReachabilityManager 是一个单例类。你不需要为 sharedManager 做 AppDelegate 初始化。

//[AFNetworkReachabilityManager sharedManager];

#import <AFNetworkReachabilityManager.h>

- (void)viewDidLoad {

//Starting the network monitoring process

[[AFNetworkReachabilityManager sharedManager]startMonitoring];

//Checking the Internet connection...

[[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
    if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {

        UIAlertView *alertNetFound = [[UIAlertView alloc]initWithTitle:@"Network Found" message:@"Please Wait Until It is loading" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertNetFound show];

    }else{
        UIAlertView *alertNetNotFound = [[UIAlertView alloc]initWithTitle:@"No Internet" message:@"Please Check Your Internet Connection Honey" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertNetNotFound show];
    }
}];

So, in this case every time the device connects to a network, it will do the startMonitoring process first and after that it will hit the status block every time and will display alert according to the status.

因此,在这种情况下,每次设备连接到网络时,它都会先执行 startMonitoring 过程,然后每次都会命中状态块并根据状态显示警报。

You can do anything according to your choice by replacing the alerts on the status block. I used this to load an webpage automatically from local storage but I removed that code for simplicity.

通过替换状态块上的警报,您可以根据自己的选择做任何事情。我使用它从本地存储自动加载网页,但为了简单起见,我删除了该代码。

Its even working with my simulator and Mac mini..

它甚至可以与我的模拟器和 Mac mini 一起使用。

Thanks

谢谢

Hope this helped.

希望这有帮助。

回答by Kakshil Shah

I use this in the app delegate ->

我在应用程序委托中使用它 - >

 func reachablityCode() {
        AFNetworkReachabilityManager.sharedManager()
        AFNetworkReachabilityManager.sharedManager().startMonitoring()
        AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock({(status) in
            let defaults = NSUserDefaults.standardUserDefaults()
            if status == .NotReachable {
                defaults.setBool(false, forKey:REACHABLE_KEY)
            }
            else {
                defaults.setBool(false, forKey: REACHABLE_KEY)
            }
            defaults.synchronize()
        })
    }

And then this in the base file ->

然后在基本文件中 ->

 func isReachable() -> Bool {
        return NSUserDefaults.standardUserDefaults().boolForKey(REACHABLE_KEY)
    }