Apple 可达性未显示警报

Posted

技术标签:

【中文标题】Apple 可达性未显示警报【英文标题】:Apple Reachability not showing alert 【发布时间】:2016-10-12 23:57:51 【问题描述】:

我在我的代码中使用 Apple 的可达性类。下面是appdelegate的代码

        NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil);

    self.reachability = Reachability.reachabilityForInternetConnection();
    self.reachability.startNotifier();

这就是 checkForReachability

func checkForReachability(notification:NSNotification)

    let remoteHostStatus = self.reachability!.currentReachabilityStatus()
    if (remoteHostStatus.rawValue == NotReachable.rawValue) 
        print("NOT REACHABLE")
        let myAlert = UIAlertController(title: "Alert", message: "Please check your internet connection.", preferredStyle: UIAlertControllerStyle.Alert)
        let okAction = UIAlertAction(title:"Try again.", style:UIAlertActionStyle.Default) 
            action in
            self.checkForReachability(notification)
        
        myAlert.addAction(okAction)
        self.window?.rootViewController?.presentViewController(myAlert, animated:true, completion:nil)
    



但是在没有网络的情况下(当我关闭wifi时)它不会弹出警报

【问题讨论】:

您是否在控制台中收到打印语句(无法访问)? 【参考方案1】:

这可能对这种情况有所帮助

我会给出最好的解决方案,希望对你有帮助。

import Foundation
import SystemConfiguration

public class ReachabilityCheck 
    class func isConnectionAvailable()->Bool

        var Status:Bool = false
        let url = NSURL(string: "http://www.apple.com/")
        let request = NSMutableURLRequest(URL: url!)
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 20.0
        request.HTTPMethod = "HEAD"

        var response: NSURLResponse?

        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

        if let httpResponse = response as? NSHTTPURLResponse 
            if httpResponse.statusCode == 200 
                Status = true
            

        
        else
        

            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure you are connected to internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        

        return Status
    

如何在其他类中访问或调用:

 if ReachabilityCheck.isConnectionAvailable() == true 

// write your code here when there is network 


【讨论】:

希望是的,如果您遇到任何问题,请告诉我

以上是关于Apple 可达性未显示警报的主要内容,如果未能解决你的问题,请参考以下文章

ios - 可达性通知多个警报

设置可达性以监控连接并显示警报

使用 AFNetworking 2 和可达性没有互联网连接警报

可达性 iOS 无法正常工作

有没有办法在 jQuery 中检查服务器的可达性测试

如何在没有互联网连接的情况下持续显示警报?