[英]Apple Reachability not showing alert
I'm using the Apple's reachability class in my code. 我在代码中使用了Apple的可达性类。 Below is the code of the appdelegate 以下是appdelegate的代码
NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil);
self.reachability = Reachability.reachabilityForInternetConnection();
self.reachability.startNotifier();
and this is checkForReachability 这是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)
}
}
But it won't pop up the alert when there is no internet(when i turn off the wifi) 但是当没有互联网时(当我关闭wifi时)它不会弹出警报
This might help in the case 在这种情况下可能会有所帮助
i will give best solution, hope its helpful. 我将提供最佳解决方案,希望对您有所帮助。
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
}
}
How to access or call in other classes: 如何访问或致电其他班级:
if ReachabilityCheck.isConnectionAvailable() == true {
// write your code here when there is network
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.