Swift WebView - 无连接模式[重复]
Posted
技术标签:
【中文标题】Swift WebView - 无连接模式[重复]【英文标题】:Swift WebView - No Connection Mode [duplicate] 【发布时间】:2015-05-11 15:40:32 【问题描述】:我目前正在使用 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()
谢谢!
【问题讨论】:
【参考方案1】:这里是完整的工作代码:
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)
【讨论】:
它没有给出错误,但应用程序崩溃了。我将 Foundation & SystemConfiguration 添加到“链接框架和库”中...... 显示你的崩溃日志 您是否更改了我代码中的类名?我更新了答案中的班级名称,检查一下。 很高兴为您提供帮助。:)以上是关于Swift WebView - 无连接模式[重复]的主要内容,如果未能解决你的问题,请参考以下文章