how to block user , if he/she not connected to internet connection when my app load

匆匆过客 提交于 2019-12-08 07:44:16

问题


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


回答1:


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.




回答2:


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.




回答3:


Launch iOS Device Settings page

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

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

}



回答4:


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

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


来源:https://stackoverflow.com/questions/36081870/how-to-block-user-if-he-she-not-connected-to-internet-connection-when-my-app-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!