在使用应用程序时丢失Reachability连接时弹出警报(IOS xcode swift)

时间:2015-07-14 07:22:25

标签: ios swift alert reachability

我是IOS应用程序开发的初学者,并希望在使用应用程序(IOS xcode swift)"时可丢失连接丢失时弹出警报, 但是我在启动我的应用时只会收到弹出警报。互联网连接丢失时,在使用我的应用程序时没有警报弹出窗口。请帮助,谢谢!

我做了什么: 1)创建一个Reachability.swift文件和worte

if(isset($_POST['document']))

2)编辑 ViewController.swift 文件,如下所示

import Foundation

public class Reachability {

class func isConnectedToNetwork()->Bool{

    var Status:Bool = false

    let url = NSURL(string: "http://google.com/")

    let request = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0        

    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
        }
    }

    return Status
 }
 }

1 个答案:

答案 0 :(得分:4)

试试这个Reachabilty课程,将其添加到您的项目中并在viewController

中执行以下操作
let reachability = Reachability.reachabilityForInternetConnection()

reachability.whenReachable = { reachability in
if reachability.isReachableViaWiFi() {
 let alertController = UIAlertController(title: "Alert", message: "Reachable via WiFi", preferredStyle: .Alert)

    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertController.addAction(defaultAction)

    presentViewController(alertController, animated: true, completion: nil)

} 
else {
let alertController = UIAlertController(title: "Alert", message: "Reachable via Cellular", preferredStyle: .Alert)

    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertController.addAction(defaultAction)

    presentViewController(alertController, animated: true, completion: nil)
    }
  }
reachability.whenUnreachable = { reachability in
let alertController = UIAlertController(title: "Alert", message: "Not Reachable", preferredStyle: .Alert)

    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertController.addAction(defaultAction)

    presentViewController(alertController, animated: true, completion: nil)
}

reachability.startNotifier()