I'm using shared class for spinner and alert. It's working but i'm getting crash issues some times.
My code in 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() {
}
}
Some times I'm getting error in this line
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
How to use properly these two alert and spinner in same class.
Which one is good to use
Write code in shared class or write code in individual class.
Here i write window for to display alert and spinner in top of all windows including navigation bar.
Aucun commentaire:
Enregistrer un commentaire