如何在同一个班级中使用Alert和Spinner?

时间:2019-04-04 05:34:07

标签: ios swift design-patterns uialertcontroller uiactivityindicatorview

我正在使用共享类进行微调和警报。它正在工作,但有时会出现崩溃问题。

我在 SharedClass

中的代码
import UIKit

class SharedClass: NSObject {

static let sharedInstance = SharedClass()

var transparentView:UIView!
var spinner = UIActivityIndicatorView()

//Show activity indicator
func activityIndicator(view:UIView) {

    DispatchQueue.main.async {
    //            if let window = UIApplication.shared.keyWindow {//Conditionally unwrap it instead of force unwrap

            //let window = UIApplication.shared.keyWindow! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
            self.transparentView = UIView()
            self.transparentView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
            self.transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
            view.addSubview(self.transparentView)

            if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
                self.spinner = UIActivityIndicatorView(style: .whiteLarge)
                self.spinner.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
            } else {
                self.spinner = UIActivityIndicatorView(style: .white)
                self.spinner.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            }
            self.spinner.center = view.center
            self.transparentView.addSubview(self.spinner)
            self.spinner.startAnimating()

            DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {//Stop spinner after 10 Sec's
                self.stopActivityIndicator()
            }
        }
//        }
}

//Stop activity indicator
func stopActivityIndicator() {
    DispatchQueue.main.async {
        self.spinner.stopAnimating()
        self.spinner.removeFromSuperview()
        self.transparentView.removeFromSuperview()//Some times getting error here
    }
}

//Present alert on top of all windows
func alertWindow(title: String, message: String) {
    //Calling
    //SharedClass.sharedInstance.alertWindow(title:"", message:"")
    DispatchQueue.main.async(execute: {
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = UIViewController()
        window.windowLevel = UIWindow.Level.alert + 1

        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert2.addAction(defaultAction2)

        window.makeKeyAndVisible()

        window.rootViewController?.present(alert2, animated: true, completion: nil)
    })
}

private override init() {

}

}

有时我在此行中出错

let window = UIApplication.shared.keyWindow!//Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

self.transparentView.removeFromSuperview()//Some times getting error here

如何在同一个班级中正确使用这两个警报和微调器。

哪个好用

在共享类中编写代码或在单个类中编写代码。

我在此处编写窗口,用于在所有窗口(包括导航栏)顶部显示警报和微调器。

2 个答案:

答案 0 :(得分:1)

请勿强行打开包装,请使用hotif-let,如下所示:

guard

要解决第二个错误,请使用可选链接

guard let window = UIApplication.shared.keyWindow else { return }

在我的一个项目中,我正在使用与您的项目类似的方法,因为我在网络通话期间使用了此方法,所以它还会启用NetworkActivity指示器:

self.transparentView?.removeFromSuperview()

答案 1 :(得分:1)

如果您在stopActivityIndicator之前致电activityIndicator,则transparentView将为nil。因此,请勿使用隐式展开的可选内容。

更改

var transparentView:UIView!

var transparentView:UIView?

,并在使用此变量时使用可选链接

self.transparentView?.removeFromSuperview()

使用警卫队获得密钥窗口

guard let window = UIApplication.shared.keyWindow else {
    return
}

警报的UIViewController扩展

extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

您可以从任何这样的视图控制器中调用此方法。它将显示在所有视图和导航栏的顶部。

self.showAlert("Alert", msg: "Alert message")