如何知道網路通不通?

iOS
  1. 1. Swift
  2. 2. OBJC Reachability

Q: 如何知道網路通不通?

Swift

  1. 將別人寫好的 Reachability 引用進來 https://github.com/ashleymills/Reachability.swift
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")
}

OBJC Reachability

  1. 引用 SystemConfiguration.Framework

  2. 將別人寫好的 Reachability 引用進來 https://github.com/tonymillion/Reachability

  3. 實作 interface

#import "Reachability.h"

@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end
  1. 實作 .m

    \- (void)testInternetConnection { internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
    internetReachableFoo.reachableBlock = ^(Reachability*reach)

    {

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Yayyy, we have the interwebs!");
    });

    };

    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Someone broke the internet :(");
    });

    };

    [internetReachableFoo startNotifier];
    }