相关疑难解决方法(0)

如何检查iOS或macOS上的活动Internet连接?

我想查看我是否在iOS上使用Cocoa Touch库或使用Cocoa库在macOS 上建立了Internet连接.

我想出了一个方法,使用一个NSURL.我这样做的方式似乎有点不可靠(因为即使谷歌有一天会失败并依赖第三方看起来很糟糕),而且如果谷歌没有回应,我可以查看其他网站的回复,在我的应用程序中看起来似乎很浪费并且不必要的开销

- (BOOL) connectedToInternet
{
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}
Run Code Online (Sandbox Code Playgroud)

我做得不好,(更不用说stringWithContentsOfURL在iOS 3.0和macOS 10.4中被弃用)如果是这样,有什么更好的方法来实现这一目标?

macos cocoa cocoa-touch reachability ios

1309
推荐指数
34
解决办法
44万
查看次数

iOS/iPhone可达性 - 如何使用Reachability.m/.h检查互联网何时丢失/无法访问

目前我正在通过apple reachability.m/.h使用该类,它可以工作,除了它通知我任何更改,我想只通知用户网络是否无法访问.目前,如果我有互联网连接,然后松散网络它告诉我.但是当你重新连接到网络时,它也告诉我,我不想要.我希望它只告诉我什么时候有丢失/没有网络.

我认为这与电话有关:

- (void)viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter]
          addObserver:self
             selector:@selector(checkNetworkStatus:)
                 name:kReachabilityChangedNotification
               object:nil];

    internetReachable = [[Reachability
                         reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName:
                     @"www.google.ca"] retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification
}
Run Code Online (Sandbox Code Playgroud)

在调用时-[NSNotificationCenter addObserver:selector:name:object:],该名称是否具有任何其他功能,然后字面上是一个名称?这是我第一次使用NSNotificationCenter,所以我不太熟悉这个问题.

编辑:

这是我的checkNetworkStatus函数:(问题是我得到"NotReachable",因为网络连接回来了,NSAlert多次关闭)

- (void) checkNetworkStatus:(NSNotification *)notice
{
        // called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)

{
    case NotReachable:
    {
        UIAlertView * …
Run Code Online (Sandbox Code Playgroud)

iphone objective-c reachability nsnotificationcenter ios

10
推荐指数
1
解决办法
3万
查看次数