1

I have one app, which is fully map view.What I need is I need to show some alert if user not connected to internet . I have done that. Here is the code :

Reachability.swift.

import Foundation
import SystemConfiguration

public class Reachability {

    class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
             return false
        }

        let isReachable = flags == .Reachable
        let needsConnection = flags == .ConnectionRequired

        return isReachable && !needsConnection

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

But what I need is : when user not connected to internet , one UIAlertView message will show. in that alert I have one OK button. So till user connect to internet , it is possible to redirect them to mobile data on/off settings or it is possible to show UIAlertView message till the user connect to internet..

Please help me out !!

Bhavin Ramani
  • 3,221
  • 5
  • 30
  • 41
user5513630
  • 1,709
  • 8
  • 24
  • 48
  • 2
    If I were a user of your app, I wouldn't care if I am connected or not when the app starts -- unless, I will need to access remote services. So, in your app, just try to connect _when_ it is requested, and when it fails due to unreachable server, let the user know. – CouchDeveloper Mar 18 '16 at 11:09

4 Answers4

0

On click of ok button in alertview you can redirect the user to desired page, calling the appropriate segue. second option if you want to block the user, just show an activity indicator with the custom message.

Ujjwal Khatri
  • 716
  • 1
  • 6
  • 19
  • Thats what i am asking , how to show uialert continuously , till user connect to internet ??? – user5513630 Mar 18 '16 at 10:42
  • You should not go for continuously showing UIAlertview, instead show the user UIActivityIndicator. which in itself shows that some process is going on. check the following for ActivityIndicator : – Ujjwal Khatri Mar 18 '16 at 10:46
  • http://stackoverflow.com/questions/593234/how-to-use-activity-indicator-view-on-iphone – Ujjwal Khatri Mar 18 '16 at 10:46
  • ok, then where i have to add this uiactivityIndicator... And how i know again user connect the internet . so stop the uiactivity indicator – user5513630 Mar 18 '16 at 10:51
  • inside my else statement ?? – user5513630 Mar 18 '16 at 10:51
  • That depends on your code logic. On high level : Just start showing activity indicator wherever you want, when your phone gets connected call a method and write the code to remove the activity indicator in this method. Hope it would help. – Ujjwal Khatri Mar 18 '16 at 11:04
0

One thing is letting users know about the network status.

Having your app built to support all of these network states is completely different thing.

Make sure your users are aware of the current network status but also make sure your application behaves accordingly to it.

And no, you cannot redirect directly to Wi-Fi Settings.

damirstuhec
  • 6,069
  • 1
  • 22
  • 39
  • Then, how to show uialert continuously , till user connect to internet ???, please give me some code explain – user5513630 Mar 18 '16 at 10:42
  • Depends on what continuously means for you. If you stick to the guidelines provided by Apple, your application should notify the user about the network status when there is an action performed by them that requires network access. Like refreshing the feed for example. I cannot give you a complete code example because your question is too abstract. A good option would be to show an alert view every time you try to reach server, for example. – damirstuhec Mar 18 '16 at 12:39
0

Launch iOS Device Settings page

Step.1 Go to Project settings --> Info --> URL Types --> Add New URL Schemes

enter image description here

Step.2 Check for internet in viewWillAppear method and show the alert

override func viewWillAppear(animated: Bool)
    {
        //check for internet
        if Reachability.isConnectedToNetwork() == true
        {
            print("Internet connection OK")

        }
        else
        {
            print("Internet connection off")

            let alertView: UIAlertView = UIAlertView(title: "Alert!", message: "Please enable internet settings", delegate: self, cancelButtonTitle: "Settings", otherButtonTitles: "Cancel")
            alertView.show()
            return
        }
    }

Step.3 Handle alert button click

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
    {
        if buttonIndex == 0
        {
                //This will open ios devices wifi settings
                UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!)
        }
        else if buttonIndex == 1
        {
            //TODO for cancel
        }
    }

Note: Do not forget to confirm UIAlertViewDelegate


See here full example code I have tested

import UIKit


class ViewController: UIViewController, UIAlertViewDelegate
{

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


    override func viewWillAppear(animated: Bool)
    {
        //check for internet
        if Reachability.isConnectedToNetwork() == true
        {
            print("Internet connection OK")
        }
        else
        {
            print("Internet connection off")

            let alertView: UIAlertView = UIAlertView(title: "Alert!", message: "Please enable internet settings", delegate: self, cancelButtonTitle: "Settings", otherButtonTitles: "Cancel")
            alertView.show()
            return
        }
    }



    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
    {
        if buttonIndex == 0
        {
                //This will open ios devices wifi settings
                UIApplication.sharedApplication().openURL(NSURL(string: "prefs:root")!)
        }
        else if buttonIndex == 1
        {
            //TODO for cancel
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
swiftBoy
  • 35,607
  • 26
  • 136
  • 135
  • Actually, what your code does??, its just an uialert to show one time or till user connect to internet it will show uialert continuously ?? – user5513630 Mar 18 '16 at 11:00
  • I added the answer as you asked, see your comment to @damirstuhec answer, let me update my answer for redirecting user to iphone setting as per network availability. – swiftBoy Mar 18 '16 at 11:03
  • in view did load i add your first section code. And i add that func method.But its not redirecting and show as usual uialert message – user5513630 Mar 18 '16 at 11:15
0

1-) Your App Target > Info > URL Types then add new URL Types like this;

enter image description here

2-) In your AppDelegate, define this variable;

var isInternetConnected = false

3-) In your UIViewController, define an AppDelegate variable then in UIViewController viewDidLoad() method, start listening connection;

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "internetNotifier:", name: kReachabilityChangedNotification, object: nil)
    Reachability.reachabilityForInternetConnection().startNotifier()
}

4-) In your internetNotifier method, check connection;

func internetNotifier(notification: NSNotification) {
    if let reachObject = notification.object as? Reachability {
        switch reachObject.isReachable() {
        case true:
            appDelegate.isInternetConnected = true
            hideAlertController()
        case false:
            appDelegate.isInternetConnected = false
            presentViewController(UIAlertController.showAlertController(), animated: true, completion: nil)
        }
    }
}

func hideAlertController() {
    if self.navigationController?.visibleViewController is UIAlertController {
         dismissViewControllerAnimated(true, completion: nil)
    }
}

5-) Create new Extension of UIAlertController in your AppDelegate;

extension UIAlertController {

    class final func showAlertController() -> UIAlertController {
        let internetController = self.init(title: "Error", message: "No internet connection. Go to Settings and open your Wi-Fİ", preferredStyle: .Alert)
        internetController.addAction(UIAlertAction(title: "Go to Settings", style: .Default, handler: { (internetController) -> Void in
            if let settingsURL = NSURL(string: "prefs:root=WIFI") where UIApplication.sharedApplication().canOpenURL(settingsURL) {
                dispatch_async(dispatch_get_main_queue()) {
                    UIApplication.sharedApplication().openURL(settingsURL)
                }
            }
        }))
        return internetController
    }

}

6-) Last and the most important step is, call your UIAlertController in AppDelegate;

func applicationWillEnterForeground(application: UIApplication) {
    if !isInternetConnected {
       window?.rootViewController?.presentViewController(UIAlertController.showAlertController(), animated: true, completion: nil)
    }
}

Because, if user go settings open network then back your application and still not connection, you need to show him your alert again. Do not forget remove your connection observer in your UIViewController;

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: kReachabilityChangedNotification, object: nil)
    Reachability.reachabilityForInternetConnection().stopNotifier()
}
Kemal Can Kaynak
  • 1,638
  • 14
  • 26