ios - Swift WebView - 无连接模式

标签 ios xcode swift uiwebview

<分区>

我目前在 Controller 中显示来自 UIWebView 的 URL 内容,我想知道,如果没有连接到设备,我如何显示一条消息或显示一个警告对话框,你需要互联网连接才能显示内容?

我有以下代码:

import UIKit

class SecondView: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.google.com")!))
        self.view.addSubview(myWebView)
    }

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

}

谢谢!

最佳答案

这里是完整的工作代码:

import UIKit
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(nil, UnsafePointer($0)).takeRetainedValue()
    }

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

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection) ? true : false
}

}


class SecondView: UICollectionViewController {

override func viewDidLoad() {
    super.viewDidLoad()


}

override func viewDidAppear(animated: Bool) {
    if Reachability.isConnectedToNetwork() {

        let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.google.com")!))
        self.view.addSubview(myWebView)

    } else {

        var alert = UIAlertController(title: "Alert", message: "you need internet connection to display the content", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
        }
    }

}

关于ios - Swift WebView - 无连接模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28959691/

相关文章:

ios - 在 iOS 和 Swift 中播放声音而不会发生内存泄漏的可重用扩展?

swift - 如何根据信标的接近程度刷新背景图像?

尽管返回 True,IOS ObjectContext 仍未保存到持久存储

ios - Swift - 三个 UIViewController 之间的自定义 Segues

ios - 使用设备的 UDID 在 Xcode 中制作 .app 文件

ios - UIVisualEffectView 变灰(不起作用)

iOS,向应用程序添加框架,影响性能

ios - 将导航堆栈中每个 ViewController 的导航栏色调/颜色更改为不同的值

android - React Native - 导航到屏幕 - 无效的 Hook 调用

ios - 应用程序右侧的 ionic 空白