`
啸笑天
  • 浏览: 3462477 次
  • 性别: Icon_minigender_1
  • 来自: China
社区版块
存档分类
最新评论

判断网络环境

 
阅读更多

https://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

我下载的是vertion2.2

 

 

开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审查的。

Reachability

Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。

在你的程序中使用

1、Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中; 2、然后将 SystemConfiguration.framework 添加进工程。

Reachability 中定义了3种网络状态。

typedefenum {

NotReachable = 0,//无连接

ReachableViaWiFi,//使用3G/GPRS网络

ReachableViaWWAN//使用WiFi网络

 

} NetworkStatus;

 

简单判断项目连接:

// 是否wifi

+ (BOOL) IsEnableWIFI {

return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);

}

// 是否网络连接

+ (BOOL) IsEnableConnection {

return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

}

 

// 是否网络连接

+ (BOOL) IsEnable3G {

return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWWAN);

}

 

 

下面是监听整个项目网络例子:

/*

File: ReachabilityAppDelegate.m
Abstract: The application's controller.

Version: 2.2

Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms.  If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple.  Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.

The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (C) 2010 Apple Inc. All Rights Reserved.

*/

#import "ReachabilityAppDelegate.h"
#import "Reachability.h"

@implementation ReachabilityAppDelegate

- (void) configureTextField: (UITextField*) textField imageView: (UIImageView*) imageView reachability: (Reachability*) curReach
{
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    BOOL connectionRequired= [curReach connectionRequired];
    NSString* statusString= @"";
    switch (netStatus)
    {
        case NotReachable:
        {
            statusString = @"Access Not Available";
            imageView.image = [UIImage imageNamed: @"stop-32.png"] ;
            //Minor interface detail- connectionRequired may return yes, even when the host is unreachable.  We cover that up here...
            connectionRequired= NO;  
            break;
        }
            
        case ReachableViaWWAN:
        {
            statusString = @"Reachable WWAN";
            imageView.image = [UIImage imageNamed: @"WWAN5.png"];
            break;
        }
        case ReachableViaWiFi:
        {
             statusString= @"Reachable WiFi";
            imageView.image = [UIImage imageNamed: @"Airport.png"];
            break;
      }
    }
    if(connectionRequired)
    {
        statusString= [NSString stringWithFormat: @"%@, Connection Required", statusString];
    }
    textField.text= statusString;
}

- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    if(curReach == hostReach)
	{
		[self configureTextField: remoteHostStatusField imageView: remoteHostIcon reachability: curReach];
        NetworkStatus netStatus = [curReach currentReachabilityStatus];
        BOOL connectionRequired= [curReach connectionRequired];

        summaryLabel.hidden =(netStatus != ReachableViaWWAN);
        NSString* baseLabel=  @"";
        if(connectionRequired)
        {
            baseLabel=  @"Cellular data network is available.\n  Internet traffic will be routed through it after a connection is established.";
        }
        else
        {
            baseLabel=  @"Cellular data network is active.\n  Internet traffic will be routed through it.";
        }
        summaryLabel.text= baseLabel;
    }
	if(curReach == internetReach)
	{	
		[self configureTextField: internetConnectionStatusField imageView: internetConnectionIcon reachability: curReach];
	}
	if(curReach == wifiReach)
	{	
		[self configureTextField: localWiFiConnectionStatusField imageView: localWiFiConnectionIcon reachability: curReach];
	}
	
}

//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
	[self updateInterfaceWithReachability: curReach];
}


- (void) applicationDidFinishLaunching: (UIApplication* )application 
{
    #pragma unused(application)
	contentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    summaryLabel.hidden = YES;        
    

    // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
    // method "reachabilityChanged" will be called. 
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];

    //Change the host name here to change the server your monitoring
    remoteHostLabel.text = [NSString stringWithFormat: @"Remote Host: %@", @"www.apple.com"];
	hostReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
	[hostReach startNotifier];
	[self updateInterfaceWithReachability: hostReach];
	
    internetReach = [[Reachability reachabilityForInternetConnection] retain];
	[internetReach startNotifier];
	[self updateInterfaceWithReachability: internetReach];

    wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
	[wifiReach startNotifier];
	[self updateInterfaceWithReachability: wifiReach];

	[window makeKeyAndVisible];
    
}
@end

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    在ios工程中如何判断当前网络环境是IPV6还是IPV4 源码下载

    以上代码示例展示了如何在iOS工程中判断网络环境,但请注意,由于Apple的安全策略,你可能无法直接通过网络可达性判断来确定IPv4和IPv6的具体地址。然而,通过分析网络可达性标志,可以确定设备当前连接的网络是否...

    Phonegap判断网络类型及状态

    cordova 3.4 版本的API 判断网络的连接状态 调用phonegap API 判断网络类型 :2G 3G 4G wifi 等等 博客: http://blog.csdn.net/aaawqqq/article/details/22220319

    iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi

    在iOS开发中,判断设备当前所连接的网络环境是2G、3G、4G、5G或WiFi是一项常见的需求。这有助于优化应用性能,比如根据网络条件选择合适的图片质量或者视频流分辨率。本文将详细介绍如何利用苹果提供的Core ...

    易语言判断网络是否连接.rar

    易语言是一种专为中国人设计的编程语言...实际应用中,我们可能需要考虑到各种网络环境,如无线网络、移动数据等,并根据需要进行适当的错误处理和用户反馈。学习和掌握这些技能,将有助于开发出更完善的网络相关应用。

    C#判断网络是否连接

    在C#编程中,判断网络是否连接以及获取连接类型是一项重要的任务,这...通过合理地使用这些工具,开发者可以构建出能够适应各种网络环境的应用程序。在进行网络编程时,理解网络接口、IP配置以及异常处理是至关重要的。

    使用JS在浏览器中判断当前网络连接状态的几种方法

    使用JS在浏览器中判断当前网络状态的几种方法如下: 1. navigator.onLine 2. ajax请求 3. 获取网络资源 4. bind() 1. navigator.onLine 通过navigator.onLine判断当前网络状态: if(navigator.onLine){ ... }...

    android判断网络连接

    在Android开发中,判断网络连接状态是至关重要的,它能够帮助开发者确保应用在不同网络环境下正常运行。这个“android判断网络连接”的demo提供了一个简洁且实用的方法来检测设备的网络状态,包括无网络连接、GPRS...

    android判断网络状态、网络运营商、网络类型

    在Android开发中,掌握如何判断网络状态、获取网络...开发者应熟练掌握这些技能,以确保应用在不同网络环境下的稳定性和用户体验。在实际开发过程中,还需考虑权限管理,确保在使用这些功能前获取了相应的用户授权。

    C#判断网络连接状态例子(winform)

    在.NET框架中,尤其是C#编程环境下,开发者经常需要处理与网络相关的任务,其中之一就是判断用户的网络连接状态。本文将详细讲解如何在Windows Forms(Winform)应用中实现这一功能,以便于创建更加智能和用户友好的...

    判断网络是否WIFI,4G, 4G+

    提供判断网络是否可用,当前是否是wifi,4g或者4g+,如果不可用,并给出提示,调转到系统网络设置界面

    网络判断,界面启动

    4. **WebSocket连接**:如果应用需要实现实时通信,可以尝试建立WebSocket连接,如果连接成功,说明网络环境支持双向通信。 5. **监听网络变化**:注册BroadcastReceiver监听网络连接状态的变化,一旦网络状态改变...

    BAT批处理脚本-网络相关操作-设置移动网关和dns.zip

    4. **条件判断和逻辑控制**:可能使用`if`语句来判断网络环境,根据不同的网络条件执行相应的设置操作,比如区分移动网络和固定网络。 5. **批处理操作流程**:批处理脚本通常包含一系列操作,例如先禁用网络接口,...

    pb 用Ping方法 判断网络是否连通 IP地址是否有效 powerbuild

    总的来说,使用PowerBuilder的Ping方法进行网络连通性和IP地址有效性的判断,涉及到对操作系统命令的调用、异常处理以及用户界面的设计。通过理解并实践这些知识点,开发者能够更好地处理网络相关的功能,提高应用的...

    c# 判断网络是否连接

    在C#编程中,判断网络是否连接以及获取连接类型是常见的需求,这通常涉及到网络编程和系统API调用。以下是一些关于如何实现这一功能的关键知识点: ...同时,要确保代码具有良好的异常处理机制,以适应网络环境的变化。

    用vfp判断计算机是否连上网络.rar

    标题中的“用vfp判断计算机是否连上网络”是指使用Visual FoxPro(VFP)这一编程语言编写程序来检测当前计算机是否已经连接到互联网。VFP是Microsoft开发的一款数据库管理和编程环境,它允许用户创建数据库应用程序...

    Android开发准确获取手机IP地址的两种方式

    "Android开发准确获取手机IP地址的...通过ConnectivityManager判断网络环境、getLocalIpAddress()获取本地IP地址和intToIp()获取WI-FI IP地址,这三种方式可以帮助我们准确获取手机IP地址,满足微信支付等操作的需求。

    安卓实现网络情况监测,网络连接是否有效,判断移动网络还是WIFI

    安卓端实现对APP实时网络的检测,可判断此时手机能否访问网络,以及判断出此时是在使用移动流量还是WIFI,代码里有解释和介绍。博客介绍可看https://blog.csdn.net/weixin_38611617/article/details/115296055

    iOS获取当前网络环境的实现方法(推荐)

    然而,这里提供的方法并不是直接使用`Reachability`,而是一种利用状态栏UI元素来判断网络环境的方式。这种方法相对简单,但可能不适用于所有情况,因为它依赖于UI结构,可能会随着iOS版本的更新而发生变化。 下面...

    PB90网络判断(ping)源码

    描述中提到的"PB 9.0 通过PING判断网络 源码"进一步强调了这个功能的实现方式。在PowerBuilder中,可以通过创建自定义函数或者事件来调用操作系统级别的命令,如ping命令,然后解析返回的结果来确定网络的可达性。...

Global site tag (gtag.js) - Google Analytics