Pregunta

Me gustaría comprobar para ver si tengo una conexión a Internet en iOS utilizando el Cocoa Touch bibliotecas o en macOS utilizando el cacao .

Se me ocurrió una manera de hacer esto utilizando un NSURL. La forma en que lo hizo parecer un poco fiable (ya que incluso Google podría ser uno mal día y confiando en un tercero parece mal), y mientras yo pueda comprobar para ver una respuesta de algunos otros sitios web de Google si no responde, sí parece un desperdicio y una sobrecarga innecesaria en mi solicitud.

- (BOOL) connectedToInternet
{
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}

Es lo que he hecho mal, (por no hablar de stringWithContentsOfURL está en desuso en IOS 3.0 y MacOS 10.4) y si es así, lo que es una mejor manera de lograr esto?

¿Fue útil?

Solución

Importante: : Esta comprobación debe siempre se realiza de forma asíncrona. La mayoría de las respuestas a continuación se síncrona así que ten cuidado de lo contrario se congelará hasta su aplicación.


Swift

1) Instalar través CocoaPods o Cartago: https://github.com/ashleymills/Reachability.swift

2) alcanzabilidad de prueba por medio cierres

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")
}

Objective-C

1) Añadir marco SystemConfiguration para el proyecto, pero no se preocupe por su inclusión en cualquier lugar

2) Añadir Tony Millones versión de Reachability.h y Reachability.m al proyecto (que se encuentra aquí: https://github.com / tonymillion / Alcanzabilidad )

3) Actualización de la sección de interfaz

#import "Reachability.h"

// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end

4) A continuación, aplicar este método en el archivo .m de su controlador de vista que se puede llamar

// 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: La clase Reachability es una de las clases más utilizados en los proyectos por lo que podría encontrarse con conflictos de nombres con otros proyectos. Si esto sucede, usted tiene que cambiar el nombre de uno de los pares de archivos Reachability.h y Reachability.m a otra cosa para resolver el problema.

Nota: El dominio se utiliza no importa. Está haciendo una prueba para una puerta de entrada a cualquier dominio.

Otros consejos

Me gusta mantener las cosas simples. A mi modo de hacer esto es:

//Class.h
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>

- (BOOL)connected;

//Class.m
- (BOOL)connected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return networkStatus != NotReachable;
}

A continuación, utilizo esto cada vez que quiero ver si tengo una conexión:

if (![self connected]) {
    // Not connected
} else {
    // Connected. Do some Internet stuff
}

Este método no espera a que los estados modificados de la red con el fin de hacer cosas. Sólo comprueba el estado cuando se pide que lo haga.

Con el código de accesibilidad de Apple, he creado una función que va a comprobar esto correctamente sin que tenga que incluir todas las clases.

Incluir el SystemConfiguration.framework en su proyecto.

Hacer un poco de importaciones:

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

Ahora acaba de llamar a esta función:

/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability
 */
+(BOOL)hasConnectivity {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    if (reachability != NULL) {
        //NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
            {
                // If target host is not reachable
                return NO;
            }

            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
            {
                // If target host is reachable and no connection is required
                //  then we'll assume (for now) that your on Wi-Fi
                return YES;
            }


            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
            {
                // ... and the connection is on-demand (or on-traffic) if the
                //     calling application is using the CFSocketStream or higher APIs.

                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                {
                    // ... and no [user] intervention is needed
                    return YES;
                }
            }

            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
            {
                // ... but WWAN connections are OK if the calling application
                //     is using the CFNetwork (CFSocketStream?) APIs.
                return YES;
            }
        }
    }

    return NO;
}

Y es iOS 5 probado para usted.

Esto solía ser la respuesta correcta, pero ahora está anticuado como usted debe suscribirse para recibir notificaciones de accesibilidad en su lugar. Este método comprueba sincrónicamente:


Puede utilizar la clase de accesibilidad de Apple. También le permitirá comprobar si Wi-Fi está habilitado:

Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.example.com"];    // Set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];

if (remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }

La clase de accesibilidad no se suministra con el SDK, sino más bien una parte de esta aplicación de ejemplo de Apple . Sólo tienes que descargar y copiar Reachability.h / m para su proyecto. Además, hay que añadir el marco SystemConfiguration a su proyecto.

Esto es una respuesta muy simple:

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
    NSLog(@"Device is connected to the Internet");
else
    NSLog(@"Device is not connected to the Internet");

La URL debe apuntar a un extremadamente pequeño sitio web. Yo uso el sitio web móvil de Google aquí, pero si tuviera un servidor web fiable Me subir un pequeño archivo con un solo carácter en ella para la velocidad máxima.

Si la comprobación de si el dispositivo es alguna manera conectado a Internet es todo lo que quiere hacer, sin duda recomendaría el uso de esta solución simple. Si necesita saber cómo está conectado el usuario, utilizando accesibilidad es el camino a seguir.

Cuidado: Esto bloqueará brevemente su hilo, mientras se carga la página web. En mi caso, esto no era un problema, pero se debe tener en cuenta esto (créditos a Brad por señalar esto).

Así es como yo hago en mis aplicaciones: Mientras que un código de respuesta de estado 200 no garantiza nada, es lo suficientemente estable como para mí. Esto no requiere tanta carga como las respuestas NSData publicados aquí, como la mía simplemente comprueba la respuesta HEAD.

Código Swift

func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: "http://www.google.com/")
    let request = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
    {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        let rsp = response as! NSHTTPURLResponse?

        completionHandler(internet:rsp?.statusCode == 200)
    })
}

func yourMethod()
{
    self.checkInternet(false, completionHandler:
    {(internet:Bool) -> Void in

        if (internet)
        {
            // "Internet" aka Google URL reachable
        }
        else
        {
            // No "Internet" aka Google URL un-reachable
        }
    })
}

Objective-C Código

typedef void(^connection)(BOOL);

- (void)checkInternet:(connection)block
{
    NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
    NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
    headRequest.HTTPMethod = @"HEAD";

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    defaultConfigObject.timeoutIntervalForResource = 10.0;
    defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        if (!error && response)
        {
            block([(NSHTTPURLResponse *)response statusCode] == 200);
        }
    }];
    [dataTask resume];
}

- (void)yourMethod
{
    [self checkInternet:^(BOOL internet)
    {
         if (internet)
         {
             // "Internet" aka Google URL reachable
         }
         else
         {
             // No "Internet" aka Google URL un-reachable
         }
    }];
}

Apple suministra código de ejemplo para comprobar si hay diferentes tipos de disponibilidad de la red. Alternativamente hay un href="http://my.safaribooksonline.com/9780321591180/ch10lev1sec3" en los desarrolladores de iPhone libro de cocina.

Nota:. Por favor, véase el comentario de @ KHG en esta respuesta con respecto a la utilización del código de accesibilidad de Apple

Se puede usar Reachability por  ( disponible aquí ).

#import "Reachability.h"

- (BOOL)networkConnection {
    return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus];
}

if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.

Apple proporciona una aplicación de ejemplo que hace exactamente esto:

Accesibilidad

Sólo la clase de accesibilidad se ha actualizado. Ahora puede utilizar:

Reachability* reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

if (remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
else if (remoteHostStatus == ReachableViaWWAN) { NSLog(@"reachable via wwan");}
else if (remoteHostStatus == ReachableViaWiFi) { NSLog(@"reachable via wifi");}

Una versión de Accesibilidad para iOS 5 es darkseed / Reachability.h . ¡No es mío! =)

Hay un aspecto agradable, y ARC-GCD utilizando modernización de Accesibilidad aquí:

Accesibilidad

Si está utilizando AFNetworking puede utilizar su propia aplicación para el estado de accesibilidad de Internet.

La mejor manera de utilizar AFNetworking es una subclase de la clase AFHTTPClient y utilizar esta clase para hacer las conexiones de red.

Una de las ventajas de utilizar este enfoque es que se puede utilizar blocks para establecer el comportamiento deseado cuando cambia el estado de disponibilidad. Suponiendo que he creado una subclase de Singleton AFHTTPClient (como se ha dicho en las "notas" en la subclasificación AFNetworking docs ) llamado BKHTTPClient, me gustaría hacer algo como:

BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
    if (status == AFNetworkReachabilityStatusNotReachable) 
    {
    // Not reachable
    }
    else
    {
        // Reachable
    }
}];

También puede comprobar la conexión Wi-Fi o conexiones WLAN en concreto con las enumeraciones AFNetworkReachabilityStatusReachableViaWWAN y AFNetworkReachabilityStatusReachableViaWiFi ( más aquí ).

He utilizado el código en esta discusión , y parece funcionar bien (lea la toda hilo!).

No he probado exhaustivamente con todo tipo imaginable de conexión (como ad hoc Wi-Fi).

muy simple .... Pruebe con estos pasos:

Paso 1:. Añadir el marco SystemConfiguration en su proyecto


Paso 2: Importar el siguiente código en el archivo de header

.
#import <SystemConfiguration/SystemConfiguration.h>

Paso 3: Utilice el método siguiente

  • Tipo 1:

    - (BOOL) currentNetworkStatus {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        BOOL connected;
        BOOL isConnected;
        const char *host = "www.apple.com";
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
        SCNetworkReachabilityFlags flags;
        connected = SCNetworkReachabilityGetFlags(reachability, &flags);
        isConnected = NO;
        isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
        return isConnected;
    }
    

  • Tipo 2:

    Importar cabecera : #import "Reachability.h"

    - (BOOL)currentNetworkStatus
    {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus networkStatus = [reachability currentReachabilityStatus];
        return networkStatus != NotReachable;
    }
    

Paso 4: Modo de empleo:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}
-(void)newtworkType {

 NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;

for (id subview in subviews) {
    if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
        dataNetworkItemView = subview;
        break;
    }
}


switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {
    case 0:
        NSLog(@"No wifi or cellular");
        break;

    case 1:
        NSLog(@"2G");
        break;

    case 2:
        NSLog(@"3G");
        break;

    case 3:
        NSLog(@"4G");
        break;

    case 4:
        NSLog(@"LTE");
        break;

    case 5:
        NSLog(@"Wifi");
        break;


    default:
        break;
}
}
- (void)viewWillAppear:(BOOL)animated
{
    NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];

    return (URL != NULL ) ? YES : NO;
}

O utilice el clase de accesibilidad .

Hay dos formas de comprobar la disponibilidad de Internet utilizando el SDK de iPhone:

1. Compruebe la página de Google se abre o no.

2. Asequibilidad Clase

Para obtener más información, por favor remítase a asequibilidad (Apple Developer).

http://huytd.github.io/datatify/ . Es más fácil que la adición de bibliotecas y código de escritura por sí mismo.

Primera : Añadir CFNetwork.framework en marco

Código : ViewController.m

#import "Reachability.h"

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}

En primer lugar descargar la clase accesibilidad y poner reachability.h y el archivo reachabilty.m en su Xcode .

La mejor manera es hacer una clase de funciones comunes (NSObject) de manera que se puede usar cualquier clase. Estos son dos métodos para un control de conexión de red asequibilidad:

+(BOOL) reachabiltyCheck
{
    NSLog(@"reachabiltyCheck");
    BOOL status =YES;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(reachabilityChanged:)
                                          name:kReachabilityChangedNotification
                                          object:nil];
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    NSLog(@"status : %d",[reach currentReachabilityStatus]);
    if([reach currentReachabilityStatus]==0)
    {
        status = NO;
        NSLog(@"network not connected");
    }
    reach.reachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    };
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    };
    [reach startNotifier];
    return status;
}

+(BOOL)reachabilityChanged:(NSNotification*)note
{
    BOOL status =YES;
    NSLog(@"reachabilityChanged");
    Reachability * reach = [note object];
    NetworkStatus netStatus = [reach currentReachabilityStatus];
    switch (netStatus)
    {
        case NotReachable:
            {
                status = NO;
                NSLog(@"Not Reachable");
            }
            break;

        default:
            {
                if (!isSyncingReportPulseFlag)
                {
                    status = YES;
                    isSyncingReportPulseFlag = TRUE;
                    [DatabaseHandler checkForFailedReportStatusAndReSync];
                }
            }
            break;
    }
    return status;
}

+ (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags)
    {
        NSLog(@"Error. Could not recover network reachability flags");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
    NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
    NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
    NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
    return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}

Ahora se puede comprobar la conexión a la red en cualquier clase llamando a este método de clase.

También hay otro método para comprobar la conexión a Internet utilizando el SDK del iPhone.

Trate de poner en práctica el siguiente código para la conexión a la red.

#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>

/**
     Checking for network availability. It returns
     YES if the network is available.
*/
+ (BOOL) connectedToNetwork
{

    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability =
        SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }

    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);

    return (isReachable && !needsConnection) ? YES : NO;
}

Me pareció simple y fácil de usar la biblioteca SimplePingHelper .

Código de ejemplo: chrishulbert / SimplePingHelper ( GitHub )

  1. Descargar el archivo de accesibilidad, https://gist.github.com/darkseed/1182373

  2. Y añadir CFNetwork.framework y 'SystemConfiguration.framework' en el marco

  3. No import "Reachability.h"


Primera : Añadir CFNetwork.framework en marco

Código : ViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}

El clase de accesibilidad es buena idea averiguar si la conexión a Internet está disponible a un dispositivo o no ...

Sin embargo, en caso de acceder a un recurso de la intranet

ping al servidor de intranet con la clase de accesibilidad siempre devuelve verdadero.

Así que una solución rápida en este escenario sería la creación de un método web llamado pingme junto con otros webmethods en el servicio. El pingme debe devolver algo.

Así que escribió el siguiente método en las funciones comunes

-(BOOL)PingServiceServer
{
    NSURL *url=[NSURL URLWithString:@"http://www.serveraddress/service.asmx/Ping"];

    NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];

    [urlReq setTimeoutInterval:10];

    NSURLResponse *response;

    NSError *error = nil;

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq
                                                 returningResponse:&response
                                                             error:&error];
    NSLog(@"receivedData:%@",receivedData);

    if (receivedData !=nil)
    {
        return YES;
    }
    else
    {
        NSLog(@"Data is null");
        return NO;
    }
}

El método anterior era tan útil para mí, por lo que cada vez que intento enviar algunos datos al servidor Siempre comprobar la accesibilidad de mi recurso de la intranet que utiliza este tiempo de espera de bajo URLRequest.

Para hacer esto mismo es extremadamente simple. El siguiente método funcionará. Sólo asegúrese de no permitir que un nombre de host protocolo como HTTP, HTTPS, etc., para ser aprobada en el nombre.

-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
    SCNetworkReachabilityFlags flags;
    if (!SCNetworkReachabilityGetFlags(ref, &flags))
    {
        return NO;
    }
    return flags & kSCNetworkReachabilityFlagsReachable;
}

Es simple rápido y sin dolor.

Además de la accesibilidad también puede utilizar la simple Ping ayudante de biblioteca . Funciona muy bien y es fácil de integrar.

Creo que ésta es la mejor respuesta.

"Sí" significa conectado. "No" significa desconectado.

#import "Reachability.h"

 - (BOOL)canAccessInternet
{
    Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStats = [IsReachable currentReachabilityStatus];

    if (internetStats == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

clase Reachable.h importación en su ViewController, y utilizar el siguiente código para comprobar conectividad

     #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
     if (hasInternetConnection){
           // To-do block
     }
  • . Paso 1: Agregue la clase de accesibilidad en su proyecto
  • Paso 2: importar la clase de accesibilidad
  • Paso 3: Crear la función a continuación

    - (BOOL)checkNetConnection {
        self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];
        NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus];
        switch (netStatus) {
            case NotReachable:
            {
                return NO;
            }
    
            case ReachableViaWWAN:
            {
                 return YES;
            }
    
            case ReachableViaWiFi:
            {
                 return YES;
            }
        }
    }
    
  • Paso 4: Llame a la función como a continuación:

    if (![self checkNetConnection]) {
        [GlobalFunctions showAlert:@""
                         message:@"Please connect to the Internet!"
                         canBtntitle:nil
                         otherBtnTitle:@"Ok"];
        return;
    }
    else
    {
        Log.v("internet is connected","ok");
    }
    

Verificación de la disponibilidad de conexión a Internet en (IOS) Xcode 8, Swift 3.0

  

Este es el método simple para comprobar la disponibilidad de la red como nuestro dispositivo está conectado a ninguna red o no. He logrado traducir a Swift 3.0 y aquí el código final. La clase de Apple de accesibilidad existentes y otras bibliotecas de terceros parecían ser demasiado complicado para traducir a Swift.

     

Esto funciona tanto para 3G, 4G y conexiones Wi-Fi.

     

No se olvide de añadir “SystemConfiguration.framework” a su constructor proyecto.

//Create new swift class file Reachability in your project.
import SystemConfiguration
public class InternetReachability {

class func isConnectedToNetwork() -> Bool {
   var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
   zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
   zeroAddress.sin_family = sa_family_t(AF_INET)
   let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
          SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
   }
   var flags: SCNetworkReachabilityFlags = 0
   if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
          return false
   }
   let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
   let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

   return isReachable && !needsConnection
  }
}

// Check network connectivity from anywhere in project by using this code.
 if InternetReachability.isConnectedToNetwork() == true {
         print("Internet connection OK")
  } else {
         print("Internet connection FAILED")
  }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top