We need to observe the REAL reachability of network. That's what RealReachability do.

Overview

RealReachability

Version License Platform Platform

We need to observe the REAL reachability of network for iOS. That's what RealReachability do.

Why RealReachability?

As we know, we already have reachability framework for us to choose. Such as the famous repository Reachability.

BUT we really need a tool for us to get the reachability, not the local connection!

Apple doc tells us something about SCNetworkReachability API: "Note that reachability does not guarantee that the data packet will actually be received by the host."

The called "reachability" we already know can only tell us the local connection status.These tools currently we know are all supported by the SCNetworkReachability API.

Now RealReachability can do this for you~

We introduce ping module for us to check the real network status, together with SCNetworkReachability API. And we use FSM(finite state machine) to control all of the network status to confirm that only status change will be sent to application.

Enjoy it!

Quick Start With Cocoapods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like RealReachability in your projects. You can install it with the following command:

$ gem install cocoapods

Podfile

To integrate RealReachability into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

pod 'RealReachability'

Then, run the following command:

$ pod install

Installation with Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

RealReachability in your Cartfile:

github "dustturtle/RealReachability"

Manual Start

If you'd rather do everything by hand, just add the folder "RealReachability" to your project, then all of the files will be added to your project.

Dependencies

  • Xcode 5.0+ for ARC support, automatic synthesis and compatibility libraries. iOS 6.0+.
  • The SystemConfiguration Framework should be added to your project.

Usage

Start to notify(we suggest you to start notify in didFinishLaunchingWithOptions):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GLobalRealReachability startNotifier];
    return YES;
}

Add Observer(anywhere you like):

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(networkChanged:)
                                             name:kRealReachabilityChangedNotification
                                           object:nil];

Observer method like below:

- (void)networkChanged:(NSNotification *)notification
{
    RealReachability *reachability = (RealReachability *)notification.object;
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    NSLog(@"currentStatus:%@",@(status));
}

Trigger realtime Reachability like below:

[GLobalRealReachability reachabilityWithBlock:^(ReachabilityStatus status) {
        switch (status)
        {
            case RealStatusNotReachable:
            {
            //  case NotReachable handler
                break;
            }
                
            case RealStatusViaWiFi:
            {
            //  case WiFi handler
                break;
            }
                
            case RealStatusViaWWAN:
            {
            //  case WWAN handler
                break;
            }
                
            default:
                break;
        }
    }];

Query currentStatus

ReachabilityStatus status = [reachability currentReachabilityStatus];

Once the reachabilityWithBlock was called, the "currentReachabilityStatus" will be refreshed synchronously.

Set your own host for Ping (optional)

Note that now we introduced the new feature "doublecheck" to make the status more reliable in 1.2.0!

Please make sure the host you set here is available for pinging. Large, stable website suggested.
This step is optional. If you do not set this, our default host is: www.apple.com.
You may set your own host any time you like. Codes just like below:

GLobalRealReachability.hostForPing = @"www.apple.com";
GLobalRealReachability.hostForCheck = @"www.youOwnHostExample.com";

We suggest you use two hosts: one your own(if you have one available for pinging), one public; Just like the example below.

For more details about the "doublecheck" feature, you can go deep into the codes.

Get current WWAN type (optional)

 WWANAccessType accessType = [GLobalRealReachability currentWWANtype];

Current WWAN type might be used to improve your app's user experience(e.g, set different network request timeout interval for different WWAN type).

Check the VPN status of your network

- (BOOL)isVPNOn;

With the help of this method, we have improved our reachability check logic when using VPN.

More:

We can also use PingHelper or LocalConnection alone to make a ping action or just observe the local connection.
Pod usage like blow (we have two pod subspecs):

pod 'RealReachability/Ping'
pod 'RealReachability/Connection'

This is the only API we need to invoke about Ping:

- (void)pingWithBlock:(void (^)(BOOL isSuccess))completion;

More about the ping usage, please see the PingHelper.h or codes in the demo project.

LocalConnection module is very similar with Reachability.
More about its usage, please see the LocalConnection.h or codes in the demo project.

Demo

We already put the demo project in the repository.

License

RealReachability is released under the MIT license. See LICENSE for details.

And finally...

Please use and improve! Patches accepted, or create an issue.

I'd love it if you could send me a note as to which app you're using it with! Thank you!

支持我

老司机技术周报出品的《WWDC 内参》系列,一直是 iOS 开发的精品阅读,几乎涵盖了每年需要了解的所有 iOS 新技术。尤其是今年《WWDC21 内参》的质量比去年有了比较大的提升, 作为作者之一,在这里安利给大家: https://xiaozhuanlan.com/wwdc21?rel=4203097925。目前活动价五折销售,抓紧入手啦。

中文版使用指南

Comments
  • 用1.1.9的版本 测试移动4G 返回的是网络不可用 有啥解决办法

    用1.1.9的版本 测试移动4G 返回的是网络不可用 有啥解决办法

    移动 4G 失败 移动 2G 失败 联通4G 可以 联通3G 可以 联通2G 可以 无线可以 电信 4G可以 电信 3G可以

    这个是测试的结果 下面的是 let struts = RealReachability.sharedInstance().currentReachabilityStatus() if struts == .RealStatusNotReachable { print("网络不给力啊") return false }else{ self.analyzeNetworkType(type: struts) return true }

    返回值就是false

    opened by hanxueshi 35
  • 从后台到前台会有crash的问题,请问下这是为什么呢

    从后台到前台会有crash的问题,请问下这是为什么呢

    3e5c5627-a7c4-4497-93d1-8bdac39ceeae

    INFO: Reveal Server started (Protocol Version 25). Assertion failed: (theHost == obj->_host), function HostResolveCallback file /Users/.../trunk/Pods/RealReachability/RealReachability/Ping/PingFoundation.m, line 575.

    opened by haojian2016 23
  • 获取蜂窝网络类型出错了,iOS12以上系统API更换了

    获取蜂窝网络类型出错了,iOS12以上系统API更换了

    CTTelephonyNetworkInfo *teleInfo = [[CTTelephonyNetworkInfo alloc] init]; NSString *accessString = teleInfo.currentRadioAccessTechnology;

    通过currentRadioAccessTechnology无法获取到,iOS12+需要通过serviceCurrentRadioAccessTechnology获取。

    opened by Abnerzj 17
  • 从wifi切换到4G状态不对

    从wifi切换到4G状态不对

    运行demo,系统是9.3.1的iphone6,从底部拉出系统菜单,关闭wifi按钮,从wifi切换到4g,会出现提示RealReachabilityStatus4G,接着再次提示为Network unreachable!从底部拉出系统菜单,打开wifi按钮,从4G切换到wifi也会出现Network wifi! Free,再次提示为Network unreachable!原因是第一次正常,第二次就都是notreachable,反复较快切换,这种情况出现的频率较为高;尤其是从wifi切换到4g,状态出现错误的概率很大(现象同前面描述);

    opened by changpk 16
  • 不知道是ios7还是因为手机是越狱的情况,判断不可用啊

    不知道是ios7还是因为手机是越狱的情况,判断不可用啊

    如题,就是我有个4s,越狱的,ios7,有做一些判断网络环境的操作,然后经常就是连着wifi,开始调试,点击,点击某个按钮进行网络请求,然后就判断成为了不是wifi个2 G 3 G 4G 的那个选项,另外2个就是一个没联网一个未知嘛。我这是连着公司wifi的,所以不知道是什么情况,求大神指教?(这个判断网不对我就只有重新commen+r)

    opened by wlerl 9
  • Crashes in multi threaded app usage.

    Crashes in multi threaded app usage.

    I get the same crash dump a lot of times. Every time, the thread that this is being done is some background thread. I noticed you are starting the pingFoundation in main thread. Do we also need to stop it in main thread?

    The below is the dump of the crash generated by Hockey

    Thread 11 Crashed: 0x0000000181e459cc CFRelease + 1128 0x00000001005f5ec0 -PingFoundation stopDataTransfer 0x00000001005f5efc -PingFoundation stop 0x00000001005f62c0 -PingHelper pingWithBlock: 0x00000001005f77a0 -RealReachability reachabilityWithBlock: 0x00000001005f7e40 __41-[RealReachability autoCheckReachability]_block_invoke (RealReachability.m:253) 0x00000001819b9630 _dispatch_call_block_and_release + 20 0x00000001819b95f0 _dispatch_client_callout + 12 0x00000001819c4e7c _dispatch_after_timer_callback + 88 0x00000001819b95f0 _dispatch_client_callout + 12 0x00000001819d0204 _dispatch_source_latch_and_call + 2552 0x00000001819bbae4 _dispatch_source_invoke + 804 0x00000001819c7504 _dispatch_root_queue_drain + 724 0x00000001819c7224 _dispatch_worker_thread3 + 108 0x0000000181bcd470 _pthread_wqthread + 1088 0x0000000181bcd020 start_wqthread + 0

    opened by skathiresan 9
  • iOS12 网络延迟问题,系统SCNetworkReachabilityRef可能有问题

    iOS12 网络延迟问题,系统SCNetworkReachabilityRef可能有问题

    iOS12 网络延迟问题,断网和连WIFI之间测试,有时网络状态返回是前一次的结果 ,有时候doubleCheck之后,返回的是正常,又或者偶尔有网络的变化检测不出,过大概几分钟又恢复正常。目前这个基于ping和SCNetworkReachabilityRef,已经是比较好的解决方案。最头痛的是在iOS12下,苹果官方给的Reachability也是只要一断网,后面的网络状态就检测不出来了,但是iOS11,10,9全部都没有这样的问题。我想应该是苹果底层的网络框架有改动了,又没有放出对应的替换API!!!

    opened by Cellphoness 8
  • iOS 9 运行报错

    iOS 9 运行报错

    check_compile_time(sizeof(ICMPHeader) == 8); check_compile_time(offsetof(ICMPHeader, type) == 0); check_compile_time(offsetof(ICMPHeader, code) == 1); check_compile_time(offsetof(ICMPHeader, checksum) == 2); check_compile_time(offsetof(ICMPHeader, identifier) == 4); check_compile_time(offsetof(ICMPHeader, sequenceNumber) == 6);

    opened by championship456 8
  • 发现一个重复发送通知问题

    发现一个重复发送通知问题

    你好,感谢提供这么优秀的开源代码。在使用过程中,我发现在切换网络的时候有时(概率并不高)会接收到两次通知,而且第二次通知事件中获取到的网络连接状态是错误的。这种情况只出现在由无网络切换到有网络的时候,也就是说,从无网络切换到有网络时,先收到了一个网络变化通知,在这个通知事件中获取到的网络状态是“连接状态”,然后又收到了另一个网络变化通知,在这个通知事件中获取到的网络状态是“不可连接状态”,这会导致程序出现异常。我跟了下代码,发现用户在收起系统快捷操作面板(就是从屏幕底部滑出的那个面板)的时候会触发reachabilityWithBlock事件,在localConnectionChanged事件后面也有触发reachabilityWithBlock事件,有可能是reachabilityWithBlock中发出了重复的通知。不知道这是不是一个bug,还是我使用的方法有问题。

    opened by wanghongbo 8
  • RealReachability Crash SomeTimes

    RealReachability Crash SomeTimes

    In My App, Bugly Reports some crashes about RealReachability libsystem_kernel.dylib | __sendto + 8 1 RealReachability | -[PingFoundation sendPingWithData:] (PingFoundation.m:313) 2 RealReachability | -[PingHelper pingFoundation:didStartWithAddress:] (PingHelper.m:159) 3 RealReachability | -[PingFoundation startWithHostAddress] (PingFoundation.m:670) 4 RealReachability | -[PingFoundation hostResolutionDone] (PingFoundation.m:723) 5 RealReachability | HostResolveCallback (PingFoundation.m:763)

    opened by CoderCMY 7
  • fix bug and add function

    fix bug and add function

    1 changed file 1、fix in bad network condition the ping checker return fail but network status possible set to reachable while not post status change notification to users; so if user call - (ReachabilityStatus)currentReachabilityStatus function return status is not match with the app UI current show state. eg: the app shows current time is in no network condition while can send out network request. 2、add when in bad network condition ping fail two times, changed reachable status to not reachable; later network become better, if ping two times return success, we consider the network is connected and change network status to reachable and post change notification to users .

    opened by iMickChen 7
  • why pinging run with mainthread

    why pinging run with mainthread

    why pinging run with mainthread? in children thread will call bug? The code :

    • (void)pingWithBlock:(void (^)(BOOL isSuccess, NSTimeInterval latency))completion { //NSLog(@"pingWithBlock"); if (completion) { // copy the block, then added to the blocks array. @synchronized(self) { [self.completionBlocks addObject:[completion copy]]; } }

      if (!self.isPinging) { // MUST make sure pingFoundation in mainThread __weak __typeof(self)weakSelf = self; if (![[NSThread currentThread] isMainThread]) { dispatch_sync(dispatch_get_main_queue(), ^{ __strong __typeof(weakSelf)strongSelf = weakSelf; [strongSelf startPing]; }); } else { [self startPing]; } } }

    opened by spencer627 0
  • Crash on PingFoundation dealloc

    Crash on PingFoundation dealloc

    根據文檔,或許我們不應該在 PingFoundation dealloc 時調用 [self stop]

    Crash call stack:

    Crashed: SearchSerialQueue (QOS: UNSPECIFIED)
    0  CFNetwork                      0xca530 CFHostUnscheduleFromRunLoop + 60
    1  RealReachability               0xa230 -[PingFoundation stopHostResolution] + 800 (PingFoundation.m:800)
    2  RealReachability               0xa2d0 -[PingFoundation stop] + 816 (PingFoundation.m:816)
    3  RealReachability               0x8d0c -[PingFoundation dealloc] + 188 (PingFoundation.m:188)
    4  RealReachability               0xa990 -[PingHelper setHost:] + 116 (PingHelper.m:116)
    
    ...
    
    opened by ohlulu 2
  • 从无网络或蜂窝数据切换到一个无网络的WiFi时会多一次RealStatusViaWiFi状态的调用

    从无网络或蜂窝数据切换到一个无网络的WiFi时会多一次RealStatusViaWiFi状态的调用

    问题描述

    2022-10-11 00:44:04.335382+0800 ocproject[28105:9359196] currentStatus:0
    2022-10-11 00:44:04.418624+0800 ocproject[28105:9359196] Successfully load keyboard extensions
    2022-10-11 00:44:04.794793+0800 ocproject[28105:9359225] Metal API Validation Enabled
    2022-10-11 00:44:48.934408+0800 ocproject[28105:9359196] currentStatus:2
    2022-10-11 00:44:50.047799+0800 ocproject[28105:9359196] currentStatus:0
    

    问题出现位置在-[RealReachability localConnectionHandler:]中的[[NSNotificationCenter defaultCenter] postNotificationName:kRealReachabilityChangedNotification object:strongSelf];

    解决方法

    可以考虑重写-[RealReachability localConnectionHandler:]方法的逻辑

    opened by shiki-z 0
Releases(1.3.0)
Owner
Zhenwei Guan
Simply the best ~
Zhenwei Guan
Make it easier to observe network connectivity in SwiftUI.

ReachabilityX ReachabilityX is built using NWPathMonitor from Apple's Network framework to provide an easy way to observe the network changes for Swif

Dscyre Scotti 8 Feb 4, 2022
Replacement for Apple's Reachability re-written in Swift with closures

Reachability.swift Reachability.swift is a replacement for Apple's Reachability sample, re-written in Swift with closures. It is compatible with iOS (

Ashley Mills 7.7k Jan 1, 2023
Another network wrapper for URLSession. Built to be simple, small and easy to create tests at the network layer of your application.

Another network wrapper for URLSession. Built to be simple, small and easy to create tests at the network layer of your application. Install Carthage

Ronan Rodrigo Nunes 89 Dec 26, 2022
A network extension app to block a user input URI. Meant as a network extension filter proof of concept.

URIBlockNE A network extension app to block a user input URI. Meant as a network extension filter proof of concept. This is just a research effort to

Charles Edge 5 Oct 17, 2022
Say goodbye to the Fat ugly singleton Network Manager with this Network Layer

MHNetwork Protocol Oriented Network Layer Aim to avoid having bloated singleton NetworkManager Philosophy the main philosophy behind MHNetwork is to h

Mohamed Emad Hegab 19 Nov 19, 2022
NWReachability - a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

NWReachability is a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

null 4 Dec 2, 2022
Easy and lightweight network layer for creating different set of network requests like GET, POST, PUT, DELETE customizable with coders conforming to TopLevelDecoder, TopLevelEncoder

Easy and lightweight network layer for creating different set of network requests like GET, POST, PUT, DELETE customizable with coders conforming to TopLevelDecoder, TopLevelEncoder

Igor 2 Sep 16, 2022
Open source SDK to quickly integrate subscriptions, stop worring about code maintenance, and getting advanced real-time data. Javascript / iOS glue framework

Open source SDK to quickly integrate subscriptions, stop worring about code maintenance, and getting advanced real-time data. Javascript / iOS glue framework

glassfy 5 Nov 7, 2022
Real-time Apps the SwiftUI way

Sync Sync is a proof of concept for expanding on the Magic of ObservableObject, and making it work over the network. This let's you create real-time A

Mathias Quintero 138 Dec 14, 2022
Dratini is a neat network abstraction layer.

Dratini Dratini is a neat network abstraction layer. If you are looking for a solution to make your network layer neat, Dratini is your choice. Dratin

Kevin Lin 37 Jan 29, 2022
Network abstraction layer written in Swift.

Moya 14.0.0 A Chinese version of this document can be found here. You're a smart developer. You probably use Alamofire to abstract away access to URLS

Moya 14.4k Jan 1, 2023
A toolkit for Network Extension Framework

NEKit NEKit is deprecated. It should still work but I'm not intent on maintaining it anymore. It has many flaws and needs a revamp to be a high-qualit

zhuhaow 2.8k Jan 2, 2023
A lightweight, one line setup, iOS / OSX network debugging library! 🦊

Netfox provides a quick look on all executed network requests performed by your iOS or OSX app. It grabs all requests - of course yours, requests from

Christos Kasketis 3.4k Dec 28, 2022
Elegant network abstraction layer in Swift.

Elegant network abstraction layer in Swift. 中文 Design Features Requirements Communication Installation Usage Base Usage - Target - Request - Download

null 100 Dec 9, 2022
Lightweight network abstraction layer, written on top of Alamofire

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-

MLSDev 528 Dec 26, 2022
iOS network debugging, like a wizard 🧙‍♂️

Start debugging iOS network calls like a wizard, without extra code! Wormholy makes debugging quick and reliable. What you can do: No code to write an

Paolo Musolino 2.1k Jan 8, 2023
A generic network layer written in swift

SwiftyNet 1.0.0 A generic network layer written in swift. you can use it as an abstraction layer above Alamofire with generic returned types. Installa

Mohamed Salah Zidane 17 Oct 11, 2021
Swift Paging is a framework that helps you load and display pages of data from a larger dataset from local storage or over network.

Swift Paging is a framework that helps you load and display pages of data from a larger dataset from local storage or over network. This approach allows your app to use both network bandwidth and system resources more efficiently. It's built on top of Combine, allowing you to harness its full power, handle errors easily, etc.

Gordan Glavaš 12 Dec 9, 2022
Automatically sets the network activity indicator for any performed request.

BigBrother BIG BROTHER IS WATCHING YOU. BigBrother is a Swift library made for iOS that automatically watches for any performed request and sets the n

Marcelo Fabri 446 Dec 17, 2022