Domanda

Mi piacerebbe controllare per vedere se ho una connessione Internet su iOS utilizzando il Cocoa Touch biblioteche o su MacOS utilizzando il Cocoa .

mi si avvicinò con un modo per farlo utilizzando un NSURL. Il modo in cui ho fatto mi sembra un po 'inaffidabile (perché anche Google potrebbe un giorno essere giù e basandosi su una terza parte sembra male), e mentre ho potuto verificare di vedere una risposta da parte di alcuni altri siti se Google non ha risposto, si non sembra in testa uno spreco e un inutile per la mia applicazione.

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

È quello che ho fatto male, (per non parlare stringWithContentsOfURL è deprecato in iOS 3.0 e MacOS 10.4) e in caso affermativo, qual è il modo migliore per raggiungere questo obiettivo?

È stato utile?

Soluzione

Importante : Questo controllo deve sempre essere eseguita in modo asincrono. La maggior parte delle risposte di seguito sono sincrona quindi state attenti altrimenti si congelare la vostra app.


Swift

1) Installare via CocoaPods o Cartagine: https://github.com/ashleymills/Reachability.swift

2) raggiungibilità test mediante chiusure

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) Aggiungere quadro SystemConfiguration al progetto, ma non preoccupatevi compreso ovunque

2) Aggiungere la versione Tony milioni di di Reachability.h e Reachability.m al progetto (che si trova qui: https://github.com / tonymillion / raggiungibilità )

3) Aggiornare la sezione di interfaccia

#import "Reachability.h"

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

4) Quindi implementare questo metodo nel file .m del controller della vista che si può chiamare

// 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 classe Reachability è una delle classi più utilizzati in progetti per cui si potrebbe incorrere in conflitti di denominazione con altri progetti. In questo caso, si dovrà rinominare una delle coppie di file Reachability.h e Reachability.m a qualcosa d'altro per risolvere il problema.

Nota: Il dominio si utilizza non importa. E 'solo il test per un gateway per qualsiasi dominio.

Altri suggerimenti

mi piace mantenere le cose semplici. Il mio modo di fare questo è:

//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;
}

Quindi, io uso questo ogni volta che voglio vedere se ho una connessione:

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

Questo metodo non aspetta che gli stati di rete modificati al fine di fare cose. E le prove solo lo stato in cui si chiede a.

Utilizzando il codice di raggiungibilità di Apple, ho creato una funzione che controllerò questo modo corretto senza dover includere tutte le classi.

Includere la SystemConfiguration.framework nel progetto.

Fare alcune importazioni:

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

Ora basta chiamare questa funzione:

/*
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;
}

Ed è iOS 5 provato per voi.

Questa era la risposta corretta, ma è ormai superata, come si dovrebbe sottoscrivere le notifiche per la raggiungibilità, invece. Questo metodo controlla in modo sincrono:


È possibile utilizzare la classe di raggiungibilità di Apple. Essa permetterà anche di controllare se la connessione Wi-Fi è attivata:

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 classe raggiungibilità non viene fornito con l'SDK, ma piuttosto una parte di questa applicazione di esempio di Apple . Basta scaricarlo, e copiare Reachability.h / m per il vostro progetto. Inoltre, si deve aggiungere il quadro SystemConfiguration al vostro progetto.

Ecco una risposta molto semplice:

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

L'URL deve puntare a un estremamente piccolo sito. Io uso il sito mobile di Google qui, ma se ho avuto un server web affidabile che avrei caricare un piccolo file con un solo personaggio in esso per la massima velocità.

Se verificare se il dispositivo è in qualche modo collegato a Internet è tutto ciò che si vuole fare, Consiglio vivamente usando questa semplice soluzione. Se avete bisogno di sapere come l'utente è collegato, tramite raggiungibilità è la strada da percorrere.

Attenzione: Questo bloccherà brevemente il tuo thread, mentre carica il sito web. Nel mio caso, questo non era un problema, ma si dovrebbe prendere in considerazione questo (crediti a Brad per la precisazione).

Ecco come lo faccio nei miei apps: Mentre un codice di risposta 200 di stato non garantisce nulla, è abbastanza stabile per me. Questo non richiede tanto carico come le risposte NSData pubblicati qui, come il mio solo verifica la risposta HEAD.

Codice 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 Codice

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
         }
    }];
}

codice di esempio per verificare la presenza di diversi tipi di disponibilità della rete. In alternativa c'è un negli sviluppatori iPhone libro di cucina.

Nota. Si prega di vedere @ commento di KHG su questa risposta per quanto riguarda l'uso del codice raggiungibilità di Apple

Si potrebbe utilizzare Reachability da  ( disponibile qui ).

#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 fornisce un'applicazione di esempio che fa esattamente questo:

raggiungibilità

Solo la classe di raggiungibilità è stato aggiornato. È ora possibile utilizzare:

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 versione sulla raggiungibilità per iOS 5 è Darkseed / Reachability.h . Non è mio! =)

C'è un bell'aspetto, ARC-e-GCD utilizzando modernizzazione della raggiungibilità qui:

raggiungibilità

Se stai usando AFNetworking è possibile utilizzare la propria implementazione per lo status di internet raggiungibilità.

Il modo migliore per utilizzare AFNetworking è quello di creare una sottoclasse della classe AFHTTPClient e utilizzare questa classe per fare le connessioni di rete.

Uno dei vantaggi dell'utilizzo di questo approccio è che si può utilizzare blocks per impostare il comportamento desiderato quando lo stato di raggiungibilità modifiche. Supponendo che ho creato una sottoclasse Singleton di AFHTTPClient (come detto sulle "note derivare sotto classi" a AFNetworking docs ) denominato BKHTTPClient, mi piacerebbe fare qualcosa di simile:

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

Si potrebbe anche verificare la presenza di connessioni WLAN Wi-Fi o specificamente utilizzando le enumerazioni AFNetworkReachabilityStatusReachableViaWWAN e AFNetworkReachabilityStatusReachableViaWiFi ( informazioni qui ).

Ho usato il codice in questa discussione , e sembra funzionare bene (leggere il tutto filo!).

Non ho provato esaurientemente con ogni tipo immaginabile di collegamento (come ad hoc Wi-Fi).

Molto semplice .... provare questi passaggi:

Passaggio 1:. Aggiungi il quadro SystemConfiguration nel progetto


Passaggio 2: Importa il seguente codice nel file header

.
#import <SystemConfiguration/SystemConfiguration.h>

Passaggio 3: Utilizzare il seguente metodo

  • 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:

    Importa intestazione : #import "Reachability.h"

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

Passo 4: Come usare:

- (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;
}

In alternativa, utilizzare il class raggiungibilità .

Ci sono due modi per controllare la disponibilità di Internet utilizzando l'iPhone SDK:

1. Controllare la pagina di Google è aperto o no.

2. Raggiungibilità Class

Per ulteriori informazioni, si prega di fare riferimento a raggiungibilità (Apple Developer).

http://huytd.github.io/datatify/ . E 'più facile che l'aggiunta di librerie e scrivere il codice da soli.

prima : Aggiungi CFNetwork.framework nel quadro

Codice : 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");
    }
}

Per prima cosa scaricare la classe raggiungibilità e mettere reachability.h e il file reachabilty.m nelle Xcode .

Il modo migliore è quello di fare una comune classe di funzioni (NSObject) in modo che si può utilizzare qualsiasi classe. Si tratta di due metodi per un controllo di connessione di rete di raggiungibilità:

+(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;
}

Ora è possibile controllare la connessione di rete in tutte le fasce chiamando questo metodo di classe.

C'è anche un altro metodo per controllare la connessione Internet utilizzando l'SDK iPhone.

Prova a implementare il seguente codice per la connessione di rete.

#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;
}

L'ho trovato semplice e facile da usare biblioteca SimplePingHelper .

Il codice di esempio: chrishulbert / SimplePingHelper ( GitHub )

  1. Scarica il file di raggiungibilità, https://gist.github.com/darkseed/1182373

  2. E aggiungere CFNetwork.framework e 'SystemConfiguration.framework' nel quadro

  3. Do # import "Reachability.h"

prima : Aggiungi CFNetwork.framework nel quadro

Codice : 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");
    }
}

class raggiungibilità è OK per scoprire se la connessione a Internet è disponibile a un dispositivo o no ...

Ma in caso di accesso a una risorsa Intranet :

Ping del server intranet con la classe raggiungibilità restituisce sempre true.

Quindi, una soluzione rapida in questo scenario sarebbe quello di creare un metodo web chiamato pingme insieme ad altri webMethods sul servizio. Il pingme deve restituire qualcosa.

Così ho scritto il seguente metodo sulle funzioni comuni

-(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;
    }
}

Il metodo di cui sopra è stato così utile per me, così ogni volta che cerco di inviare alcuni dati al server ho sempre controllare la raggiungibilità della mia risorsa Intranet utilizzando questo basso timeout URLRequest.

Per fare questo se stessi è estremamente semplice. Il seguente metodo funzionerà. Basta essere sicuri di non consentire un protocollo hostname come HTTP, HTTPS, ecc per essere passato con il nome.

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

È rapido semplice e indolore.

A parte la raggiungibilità si può anche utilizzare il Simple Ping aiutante biblioteca . Funziona davvero bello ed è semplice da integrare.

Credo che questo è la migliore risposta.

"Sì" significa collegato. "No" significa disconnesso.

#import "Reachability.h"

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

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

Importa classe Reachable.h nel vostro ViewController, e utilizzare il seguente codice per controllare connettività :

     #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
     if (hasInternetConnection){
           // To-do block
     }
  • Passaggio 1:. Aggiungere la classe di raggiungibilità nel progetto
  • Passaggio 2: Importare la classe di raggiungibilità
  • Passaggio 3: Creare la funzione seguente

    - (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;
            }
        }
    }
    
  • Passo 4: Chiamare la funzione, come di seguito:

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

Verifica della disponibilità connessione a Internet in (iOS) Xcode 8, Swift 3.0

  

Questo è il metodo semplice per controllare la disponibilità della rete come il nostro dispositivo è connesso a una rete o meno. Sono riuscito a tradurlo per Swift 3.0 e qui il codice finale. L'attuale classe di Apple di raggiungibilità e di altre librerie di terze parti sembravano essere troppo complicato da tradurre in Swift.

     

Questo funziona sia per il 3G, 4G e connessioni WiFi.

     

Non dimenticate di aggiungere “SystemConfiguration.framework” al costruttore progetto.

//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")
  }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top