Importante : Essa verificação sempre deve ser realizada de forma assíncrona. A maioria das respostas abaixo é síncrona, portanto, tenha cuidado, caso contrário, você congelará seu aplicativo.
Rápido
1) Instale via CocoaPods ou Carthage: https://github.com/ashleymills/Reachability.swift
2) Teste de acessibilidade via fechamentos
let reachability = Reachability()!
reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
reachability.whenUnreachable = { _ in
print("Not reachable")
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
Objetivo-C
1) Adicione SystemConfigurationestrutura ao projeto, mas não se preocupe em incluí-la em qualquer lugar
2) Adicione a versão Reachability.he Reachability.mo projeto de Tony Million (encontrado aqui: https://github.com/tonymillion/Reachability )
3) Atualize a seção da interface
#import "Reachability.h"
// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
Reachability *internetReachableFoo;
}
@end
4) Em seguida, implemente esse método no arquivo .m do seu controlador de exibição, que você pode chamar
// Checks if we have an internet connection or not
- (void)testInternetConnection
{
internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
// Internet is reachable
internetReachableFoo.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Yayyy, we have the interwebs!");
});
};
// Internet is not reachable
internetReachableFoo.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Someone broke the internet :(");
});
};
[internetReachableFoo startNotifier];
}
Nota importante: A Reachabilityclasse é uma das classes mais usadas em projetos, portanto, você pode encontrar conflitos de nomenclatura com outros projetos. Se isso acontecer, você precisará renomear um dos pares de arquivos Reachability.he Reachability.mpara outra coisa para resolver o problema.
Nota: O domínio que você usa não importa. É apenas um teste para um gateway para qualquer domínio.
return (BOOL)URLString;, ou melhor ainda,return !!URLStringoureturn URLString != nil