【问题标题】:how to block user , if he/she not connected to internet connection when my app load如何阻止用户,如果他/她在我的应用程序加载时没有连接到互联网连接
【发布时间】:2016-03-18 10:23:42
【问题描述】:

我有一个应用程序,它是完整的地图视图。我需要的是,如果用户没有连接到互联网,我需要显示一些警报。我已经做到了。这是代码:

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

但我需要的是:当用户未连接到互联网时,会显示一条UIAlertView 消息。在那个警报中,我有一个OK 按钮。因此,在用户连接到互联网之前,可以将他们重定向到移动数据开/关设置,或者可以显示UIAlertView 消息直到用户连接到互联网..

请帮帮我!!

【问题讨论】:

  • 如果我是您的应用程序的用户,我不会在意应用程序启动时是否已连接——除非我需要访问远程服务。因此,在您的应用程序中,只需尝试连接何时请求它,当由于无法访问服务器而失败时,让用户知道。

标签: ios swift reachability


【解决方案1】:

点击 alertview 中的 ok 按钮,您可以将用户重定向到所需的页面,调用适当的 segue。第二个选项,如果你想阻止用户,只需显示一个带有自定义消息的活动指示器。

【讨论】:

  • 这就是我要问的,如何连续显示uialert,直到用户连接到互联网???
  • 您不应该继续显示 UIAlertview,而是显示用户 UIActivityIndi​​cator。这本身就表明正在进行某些过程。检查以下 ActivityIndi​​cator :
  • 好的,那么我必须在哪里添加这个 uiactivityIndi​​cator... 以及我如何再次知道用户连接互联网。所以停止 uiactivity 指示器
  • 在我的 else 语句中??
【解决方案2】:

一件事是让用户了解网络状态。

让您的应用支持所有这些网络状态是完全不同的事情。

确保您的用户了解当前的网络状态,同时确保您的应用程序的行为与之相应。

不,您不能直接重定向到 Wi-Fi 设置。

【讨论】:

  • 那么,如何持续显示uialert,直到用户连接到互联网???,请给我一些代码解释
  • 取决于持续对您意味着什么。如果您遵守 Apple 提供的指南,您的应用程序应在用户执行需要网络访问的操作时通知用户网络状态。例如刷新提要。我不能给你一个完整的代码示例,因为你的问题太抽象了。例如,一个不错的选择是在每次尝试访问服务器时显示警报视图。
【解决方案3】:

启动 iOS 设备设置页面

Step.1 转到项目设置 --> 信息 --> URL 类型 --> 添加新的 URL 方案

Step.2 在 vi​​ewWillAppear 方法中检查互联网并显示警报

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处理警报按钮点击

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

注意:别忘了确认UIAlertViewDelegate


查看这里完整示例代码我已经测试过

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

}

【讨论】:

  • 实际上,你的代码是做什么的??它只是一个显示一次的 uialert 或者直到用户连接到互联网它才会连续显示 uialert ??
  • 我按照您的要求添加了答案,请参阅您对@damirstuhec 答案的评论,让我根据网络可用性更新我的答案,以将用户重定向到 iphone 设置。
  • 在视图中加载我添加了您的第一部分代码。我添加了那个 func 方法。但它没有重定向并像往常一样显示 uialert 消息
【解决方案4】:

1-) 您的应用目标 > 信息 > URL 类型,然后像这样添加新的 URL 类型;

2-) 在您的 AppDelegate 中,定义此变量;

var isInternetConnected = false

3-) 在您的UIViewController 中,定义一个AppDelegate 变量然后在UIViewController viewDidLoad() 方法中,开始监听连接;

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-) 在您的 internetNotifier 方法中,检查连接;

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-) 在您的AppDelegate 中创建UIAlertController 的新扩展;

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-) 最后也是最重要的一步是,在 AppDelegate 中调用您的UIAlertController;

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

因为,如果用户去设置打开网络然后返回您的应用程序并且仍然没有连接,您需要再次向他显示您的警报。不要忘记删除UIViewController 中的连接观察者;

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: kReachabilityChangedNotification, object: nil)
    Reachability.reachabilityForInternetConnection().stopNotifier()
}

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多