Reachability
2015-12-16 17:39
295 查看
iOS SDK: Detecting Network Changes with Reachability
by BartJacobs
Most mobile applications access the web for some reason or another. This implies that these applications will - or should - behave differently when no network connection is available. In this quick tip, I
will show you how to detect network interface changes using Tony Million's Reachability class.
Solutions
Even though Apple provides samplecode for monitoring changes in network availability, Apple's Reachability class is a bit outdated and doesn't support ARC (Automatic Reference Counting). If you use AFNetworking,
then you may want to consider
AFHTTPClient, which also lets you monitor network interface
changes.
However, my preferred solution is the wonderful Reachability
class created and maintained by Tony Million. It supports ARC and leverages GCD (Grand Central Dispatch).
Let me show you how to integrate Tony's Reachability class.
1. Setting Up the Project
Create a new project in Xcode by selecting the Single View Application template from the list of templates (figure 1). Name your application Reachability, enter a company identifier, set iPhone for the device family,and check Use Automatic Reference Counting. The rest of the checkboxes can be left unchecked for this project (figure 2). Tell Xcode where you want to save the project and click Create.
Figure 1: Choosing a Project Template
Figure 2: Configuring the Project
2. Integrating Reachability
Step 1: Adding the Reachability Class
Integrating Tony Million's Reachability class is trivial. Visit the project'sGitHub page, download the latest version, and drag Reachability.h/.m into your Xcode project (figure 3). If you take this path, make sure to copy the class files into your Xcode project (figure 4). You can also use CocoaPods to
to add Reachability to your project.
Figure 3: Adding the Reachability Class to Your Project
Figure 4: Make Sure to Copy the Class Files into Your Project
Step 2: Linking Against the System Configuration Framework
The Reachability class depends on the System Configuration framework for some of its functionality. With your project selected in the Project Navigator, select the Reachability targetin the list of targets, open the Build Phases tab, and expand the Link Binary with Libraries drawer. Click the plus button and search for SystemConfiguration.framework (figure 5).
Figure 5: Link Your Project Against the System Configuration Framework
3. Reachability Basics
The Reachabilityclass provides two
ways to monitor changes in network availability: blocks and notifications. Let me show you how this works.
Step 1: Importing Reachability.h
To keep things simple, we will add the reachability logic to the application delegate. Start by adding an import statement for Reachability.h to MTAppDelegate.m as shown below.
Step 2: Blocks
We first need to create an instance of the Reachabilityclass
in
application:didFinishLaunchingWithOptions:(MTAppDelegate.m) as shown below. We
then set the
reachableBlockand
unreachableBlockon
the
Reachabilityinstance. The
reachableBlockis
invoked when the network availability changes from unreachable to reachable. The reverse is true for the
unreachableBlock.
It is key to send the
Reachabilityinstance a message of
startNotifierso
that it knows that it should start monitoring for reachability changes. It is also important to know that the call to
startNotifiercauses
the
Reachabilityinstance to retain itself, which means that you don't need to store
a reference to the
Reachabilityobject. However, I am not a fan of this approach
and will show you an alternative solution a bit later.
when the network interface changes.
Step 3: Notifications
The advantage of using notifications for reachability changes is that any object in your application can register itself as an observer for these notifications. In contrast to the use of blocks, the reachabilitynotifications are posted and delivered on the main thread. As you can see below, in
application:didFinishLaunchingWithOptions:,
we create an instance of the
Reachabilityclass and tell it to start monitoring for
network changes.
Reachabilityinstance
posts. Open
MTViewController.m, add an import statement for Reachability.h, and update
initWithNibName:bundle:as
shown below.
reachabilityDidChange:is
invoked and the view controller can respond appropriately. The
objectproperty of
the notification is the
Reachabilityinstance that posted the notification. The
Reachabilityclass
provides a number of useful instance methods, such as
isReachable,
isReachableViaWWAN,
and
isReachableViaWiFi. You can even tell the
Reachabilityinstance
whether it should consider WWAN as unreachable by setting the
reachableOnWWANproperty
accordingly.
4. Reachability Manager
For applications that require a network connection, I usually use an alternative approach for managing reachability. I create a separate class named ReachabilityManager that adopts the singleton pattern. The singletonobject manages a
Reachabilityinstance and provides a number of useful class methods.
Let me walk you through the internals of this class.
Step 1: Interface
As I mentioned, the MTReachabilityManagerclass
adopts the singleton pattern and it provides access to the singleton object through the
sharedManagerclass
method. This is useful if an object needs direct access to the
reachabilityinstance
that the singleton object manages.
Through a number of class methods objects can ask the reachability manager about the current network interface. In addition, objects can still add themselves as observers for the
kReachabilityChangedNotificationnotifications
as we saw earlier.
Step 2: Implementation
The implementation of MTReachabilityManagerisn't
too surprising. If you are unfamiliar with the singleton pattern, then the implementation of
sharedManagermight
seem a bit odd. Even though the
MTReachabilityManagerclass makes use of the singleton
pattern, it is technically possible to create instances of the class. We could prevent this by checking the value of
_sharedManagerin
the
init, but I assume that whoever uses the
MTReachabilityManagerclass
has taken a look at the class's interface file revealing that it adopts the singleton pattern.
Reachabilityclass,
then don't forget to instantiate the singleton object when your application launches. You can do so by calling
sharedManageron
the
MTReachabilityManagerclass.
Conclusion
Notifying the user or updating the application's user interface when the network interface changes not only results in a better user experience, Apple requires that you do this if your application relies on networkconnectivity. It does take some effort, but the Reachability class makes it a lot easier.
相关文章推荐
- cuda线程/线程块索引小结
- 开启博客新风格
- nodejs 中的 NODE_PATH
- 跳转到距锚点固定位移的地方
- 边框圆角效果
- 数据库oracle-模块ExtProc或PLSExtProc介绍
- yunos系统的成功之路
- View滑动的七种方法
- 浅析Tomcat之Pipeline和Value
- Python数据类型:列表、阵列
- CityEngine中的坐标系统
- codecademy笔记,二维list
- QTreeWidget树的三态操作
- OC对文本的操作
- StringBuffer代码优化
- ie 7/8/9 placeholder 不显示 解决方案
- 机器学习入门(一)朴素贝叶斯解析
- 应用EL表达式显示客户端能够接收的内容类型
- oracle11G使用DGbroker创建dg
- iframe自适应高度