3

I am a beginner of IOS app development and would like to "popup alert when Reachability connection is lost during using the app (IOS xcode swift)", but I only get popup alert when starting the my app. There is not alert popup during using my app when internet connection lost. Please kindly help, thanks!

What I did: 1) creat a Reachability.swift file and worte

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

2) edit the ViewController.swift file as below

import UIKit
class ViewController: UIViewController {

@IBOutlet weak var WebView: UIWebView!

//ViewDidLoad method
override func viewDidLoad() {
    super.viewDidLoad()

    if Reachability.isConnectedToNetwork() == true {
        println("Internet connection OK")
    } else {
        println("Internet connection FAILED")
        var alert = UIAlertView(title: "No Internet Connection",
                                message: "Make sure your device is connected to the internet.", 
                                delegate: nil, 
                                cancelButtonTitle: "OK")

        alert.show()

    }
    var URL = NSURL(string: "http://www.google.com/")

    WebView.loadRequest(NSURLRequest(URL: URL!))
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}
Tejas
  • 1,050
  • 12
  • 23
Eric Chong
  • 495
  • 1
  • 7
  • 21

1 Answers1

4

Try this Reachabilty class, add it in your project and do the following in your 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()
iAnurag
  • 9,286
  • 3
  • 31
  • 48
  • thanks, but I am really a beginner, please kindly guide me step by step how to do it. – Eric Chong Jul 14 '15 at 10:40
  • 1.)add reachability.swift file into your project. 2)and paste above code either in your viewDidLoad method. or applicationDidFinishLaunchingWithOptions method. and run the code – iAnurag Jul 14 '15 at 10:50
  • thank you very much! I follow your answer and it works 99%. I put your viewDidLoad method of ViewController. – Eric Chong Jul 14 '15 at 11:08
  • The only problem now is that there is no alert when starting the app without internet connection. Can you help ? – Eric Chong Jul 14 '15 at 11:09
  • instead of println put your alert code bro. And UIAlertView is depricated in iOS8. use UIAlertController – iAnurag Jul 14 '15 at 11:13
  • yes, i did. Thats why it shows alert, if the app started and then connection fail. But if no connection now and start the app, there is no alert. Code " reachability.whenUnreachable = { reachability in println("Not reachable") var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK") alert.show() } – Eric Chong Jul 14 '15 at 11:16
  • use self.presentviewController in viewDidLoad – iAnurag Jul 14 '15 at 11:41
  • No error now, but same as before. There is no alert when starting the app without internet connection. – Eric Chong Jul 14 '15 at 11:46
  • dispatch_async is exist in my project, I search it on the web and it is too complicate for me to understand at the moment, i need time to investegate it. – Eric Chong Jul 14 '15 at 12:23