现在我想实现检测网络从开始到应用程序将检测是否链接网络,假设用户在途中切断网络,屏幕将显示标签和imageView,如果网络重新连接,你可以自动显示信息,让标签和imageView消失,但现在我不知道如何自动检测网络,标签和imageView如何把屏幕的中心(不使用故事板),谢谢!
这是我的代码:
func laodingTableviewData() {
self.tableView.isHidden = true
let activityIndicatorView = NVActivityIndicatorView(frame:CGRect(x:ActivityConstraint.Activity.offsetX, y:ActivityConstraint.Activity.offsetY , width:80.0, height:80.0), type: .ballSpinFadeLoader, color: ActivityConstraint.Activity.color, padding: 20)
self.view.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
//detect network
guard Reachability.isConnectedToNetwork() == true else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
self.failNetworkAlert()
self.failNetworkOutlet()
activityIndicatorView.stopAnimating()
}
return
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) {
self.bulletinBoards = BulletinBoard.downloadAllBulletinBoard()
self.tableView.isHidden = false
self.tableView.reloadData()
activityIndicatorView.stopAnimating()
}
}
创建标签和图像视图:
func failNetworkOutlet() {
let w = self.view.frame.width/2
let h = self.view.frame.height/2
let label = UILabel(frame: CGRect(x: -30, y: 0, width: 250, height: 21))
label.center = CGPoint(x: w+5, y: h)
label.textAlignment = .center
label.text = "Please confirm that you are connected to the web"
label.font = label.font.withSize(20)
label.tintColor = UIColor.gray
let imageViewObject = UIImageView(frame:CGRect(x: w-25, y: h-85, width: 60, height: 60))
imageViewObject.image = UIImage(named:"ic_settings_input_antenna_48pt")?.withRenderingMode(.alwaysTemplate)
imageViewObject.tintColor = UIColor.gray
self.view.addSubview(imageViewObject)
self.view.addSubview(label)
}
答案 0 :(得分:2)
您可以检查可达性的网络通知。然后发布一些通知,以便我们知道网络状态
import UIKit
import ReachabilitySwift
class ViewController: UIViewController {
let reachability = Reachability()
override func viewDidLoad() {
super.viewDidLoad()
checkNetworkStatus()
}
fileprivate func checkNetworkStatus() {
if let reachability = reachability {
reachability.whenReachable = { [unowned self] reachable in
self.postNetworkStatusChangedNotification(to: true)
}
reachability.whenUnreachable = { [unowned self] unreachable in
self.postNetworkStatusChangedNotification(to: false)
}
//start the notifier
do {
try reachability.startNotifier()
}
catch {
print("Unable to start the network notifier")
}
}
}
func postNetworkStatusChangedNotification(to acquired:Bool) {
//we will post notification
if acquired {
print("\n=== Internet Acess Acquired ===\n")
}
else {
print("\n=== Lost Internet Access ===\n")
}
}
}
启动时,只要网络状态发生变化,它就会通知。