Iphone 正在检查internet连接iOS 5

Iphone 正在检查internet连接iOS 5,iphone,ios5,automatic-ref-counting,reachability,connectivity,Iphone,Ios5,Automatic Ref Counting,Reachability,Connectivity,我正在制作一个应用程序,在某些地区需要连接互联网。 我正在寻找检查internet连接并返回警报视图的最佳方法。 我已经试过了,在iOS 4中只能找到实现上述功能的方法,但我正在制作的应用程序是在iOS 5中 我已经看过苹果的示例代码,但当我尝试和实现时,这只会让我的代码错误变得疯狂(因为它是为iOS4构建的) 编辑: 当我将reachability.h文件导入到我的项目中时,我得到了10个错误(其中6个我可以简单地修复),还有4个我不确定该怎么办。我已经调整了Apple的reachabilit

我正在制作一个应用程序,在某些地区需要连接互联网。 我正在寻找检查internet连接并返回警报视图的最佳方法。 我已经试过了,在iOS 4中只能找到实现上述功能的方法,但我正在制作的应用程序是在iOS 5中

我已经看过苹果的示例代码,但当我尝试和实现时,这只会让我的代码错误变得疯狂(因为它是为iOS4构建的)

编辑:
当我将reachability.h文件导入到我的项目中时,我得到了10个错误(其中6个我可以简单地修复),还有4个我不确定该怎么办。

我已经调整了Apple的
reachability
类以用于ARC,试试看

/*

 File: Reachability.m
 Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.

 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 <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>

#import <CoreFoundation/CoreFoundation.h>

#import "Reachability.h"

#define kShouldPrintReachabilityFlags 0

static void PrintReachabilityFlags(SCNetworkReachabilityFlags    flags, const char* comment)
{
#if kShouldPrintReachabilityFlags

    NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
          (flags & kSCNetworkReachabilityFlagsIsWWAN)               ? 'W' : '-',
          (flags & kSCNetworkReachabilityFlagsReachable)            ? 'R' : '-',

          (flags & kSCNetworkReachabilityFlagsTransientConnection)  ? 't' : '-',
          (flags & kSCNetworkReachabilityFlagsConnectionRequired)   ? 'c' : '-',
          (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)  ? 'C' : '-',
          (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
          (flags & kSCNetworkReachabilityFlagsConnectionOnDemand)   ? 'D' : '-',
          (flags & kSCNetworkReachabilityFlagsIsLocalAddress)       ? 'l' : '-',
          (flags & kSCNetworkReachabilityFlagsIsDirect)             ? 'd' : '-',
          comment
          );
#endif
}


@implementation Reachability
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
    NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback");
    NSCAssert([(NSObject*) objc_unretainedObject(info) isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback");

    //We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
    // in case someon uses the Reachablity object in a different thread.
    @autoreleasepool {    
        Reachability* noteObject = (Reachability*) objc_unretainedObject(info);
        // Post a notification to notify the client that the network reachability changed.
        [[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
    }
}

- (BOOL) startNotifier
{
    BOOL retVal = NO;
    const void *pointer = objc_unretainedPointer(self);
    SCNetworkReachabilityContext context = {0, (void *) pointer, NULL, NULL, NULL};
    if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
    {
        if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
        {
            retVal = YES;
        }
    }
    return retVal;
}

- (void) stopNotifier
{
    if(reachabilityRef!= NULL)
    {
        SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    }
}

- (void) dealloc
{
    [self stopNotifier];
    if(reachabilityRef!= NULL)
    {
        CFRelease(reachabilityRef);
    }
}

+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
{
    Reachability* retVal = NULL;
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
    if(reachability!= NULL)
    {
        retVal= [[self alloc] init];
        if(retVal!= NULL)
        {
            retVal->reachabilityRef = reachability;
            retVal->localWiFiRef = NO;
        }
    }
    return retVal;
}

+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
{
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
    Reachability* retVal = NULL;
    if(reachability!= NULL)
    {
        retVal= [[self alloc] init];
        if(retVal!= NULL)
        {
            retVal->reachabilityRef = reachability;
            retVal->localWiFiRef = NO;
        }
    }
    return retVal;
}

+ (Reachability*) reachabilityForInternetConnection;
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    return [self reachabilityWithAddress: &zeroAddress];
}

+ (Reachability*) reachabilityForLocalWiFi;
{
    struct sockaddr_in localWifiAddress;
    bzero(&localWifiAddress, sizeof(localWifiAddress));
    localWifiAddress.sin_len = sizeof(localWifiAddress);
    localWifiAddress.sin_family = AF_INET;
    // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
    localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
    Reachability* retVal = [self reachabilityWithAddress: &localWifiAddress];
    if(retVal!= NULL)
    {
        retVal->localWiFiRef = YES;
    }
    return retVal;
}

#pragma mark Network Flag Handling

- (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags
{
    PrintReachabilityFlags(flags, "localWiFiStatusForFlags");

    BOOL retVal = NotReachable;
    if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
    {
        retVal = ReachableViaWiFi;  
    }
    return retVal;
}

- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
{
    PrintReachabilityFlags(flags, "networkStatusForFlags");
    if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
    {
        // if target host is not reachable
        return NotReachable;
    }

    BOOL retVal = NotReachable;

    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
        retVal = ReachableViaWiFi;
    }


    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
            retVal = ReachableViaWiFi;
        }
    }

    if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
    {
        // ... but WWAN connections are OK if the calling application
        //     is using the CFNetwork (CFSocketStream?) APIs.
        retVal = ReachableViaWWAN;
    }
    return retVal;
}

- (BOOL) connectionRequired;
{
    NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");
    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
    {
        return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
    }
    return NO;
}

- (NetworkStatus) currentReachabilityStatus
{
    NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
    NetworkStatus retVal = NotReachable;
    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
    {
        if(localWiFiRef)
        {
            retVal = [self localWiFiStatusForFlags: flags];
        }
        else
        {
            retVal = [self networkStatusForFlags: flags];
        }
    }
    return retVal;
}
@end
/*
文件:Reachability.m
摘要:关于如何使用SystemConfiguration可达性API的基本演示。
版本:2.2
免责声明:重要提示:本苹果软件由苹果公司提供给您。
(“苹果”)鉴于您同意以下条款
使用、安装、修改或重新分发本Apple软件
构成对这些条款的接受。如果您不同意这些条款,
请不要使用、安装、修改或重新分发此Apple软件。
考虑到您同意遵守以下条款,并且
根据这些条款,苹果授予您个人的、非独占的许可
本原始苹果软件(以下简称“苹果软件”)的苹果版权
使用、复制、修改和重新发布Apple软件,无论是否使用
源代码和/或二进制形式的修改;前提是如果你重新分配
您必须保留完整的苹果软件,且不得进行任何修改
本通知以及所有此类再分配中的以下文本和免责声明
苹果的软件。
不得使用苹果公司的名称、商标、服务标志或徽标
在没有特别说明的情况下,支持或推广源自苹果软件的产品
苹果公司的事先书面许可。除非本通知中明确说明,
苹果在此不授予任何其他明示或暗示的权利或许可,
包括但不限于贵方可能侵犯的任何专利权
衍生作品或苹果软件可能存在的其他作品
合并。
Apple软件由Apple按“原样”提供。苹果不做任何事
明示或默示保证,包括但不限于默示
对特定产品的非侵权、适销性和适用性的保证
目的,关于苹果软件或其单独使用和操作,或
与您的产品相结合。
在任何情况下,苹果公司均不对任何特殊、间接、附带或不可抗力事件负责
间接损害(包括但不限于采购替代品
商品或服务;使用、数据或利润损失;或业务中断)
因使用、复制、修改和/或
不过苹果软件的发行是否引起了理论上的争议
合同、侵权行为(包括过失)、严格责任或其他,即使
苹果公司已被告知可能发生此类损害。
版权所有(C)2010苹果公司。保留所有权利。
*/
#进口
#进口
#进口
#进口
#进口
#进口
#进口
#导入“可达性.h”
#定义kshoulPrintReachabilityFlags 0
静态无效PrintReachabilityFlags(SCNetworkReachabilityFlags标志,常量字符*注释)
{
#如果kshoulprint可达性滞后
NSLog(@“可达性标志状态:%c%c%c%c%c%c%c%c%s\n”,
(标志和kSCNetworkReachabilityFlagsIsWWAN)?“W”:“-”,
(标志和kSCNetworkReachabilityFlagsReachable)?'R':'-',
(标志和KSCNetworkReachabilityFlagsTranssientConnection)?'t':'-',
(需要标志和KSCNetworkReachabilityFlagsConnection)?“c”:“-”,
(标志和KSCNetworkReachabilityFlagsConnectionContraffic)?'C':'-',
(需要标志和KSCNetworkReachabilityFlagsIntervationRequired)?“i”:“-”,
(标志和kSCNetworkReachabilityFlagsConnectionOnDemand)?'D':'-',
(标志和kSCNetworkReachabilityFlagsIsLocalAddress)?“l”:“-”,
(标志和kSCNetworkReachabilityFlagsIsDirect)?“d”:“d”-”,
评论
);
#恩迪夫
}
@实现可达性
静态无效可达性回调(SCNetworkReachabilityRef目标、SCNetworkReachabilityFlags标志、无效*信息)
{
#pragma未使用(目标、标志)
NSCAssert(info!=NULL,@“info在ReachabilityCallback中为NULL”);
NSCAssert([(NSObject*)objc_unretainedObject(info)是类的种类:[可达性类]],@“info在可达性回调中是错误的类”);
//我们在主运行循环中,因此NSAutoreleasePool不是必需的,而是在防御上添加的
//如果someon在不同的线程中使用reachability对象。
@自动释放池{
可达性*noteObject=(可达性*)对象未恢复对象(信息);
//发布通知,通知客户端网络可达性已更改。
[[NSNotificationCenter defaultCenter]postNotificationName:kReachabilityChangedNotification对象:noteObject];
}
}
-(BOOL)startNotifier
{
BOOL-retVal=NO;
const void*pointer=objc_未恢复指针(self);
SCNetworkReachabilityContext上下文={0,(void*)指针,NULL,NULL,NULL};
if(scnetworkreachabilitycallback(reachabilityRef、ReachabilityCallback和context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef,CFRunLoopGetCurrent(),kCFRunLoopDefaultMode))
{
retVal=是;
}
}
返回返回;
}
-(void)停止通知程序
{
if(reachabilityRef!=NULL)
{
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef,CFRunLoopGetCurrent(),kCFRunLoopDefaultMode);
}
}
-(无效)解除锁定
{
[自动停止通知程序];
if(reachabilityRef!=NULL)
{
CFRelease(可达性ref);
}
}
+(可达性*)具有主机名的可达性: