I'm trying to figure out the correct way to close the current UISceneSession. The requestSceneSessionDestruction API on UIApplication requires a UISceneSession object which has been tricky to get. The close API also might return an NSError when closing the session, but I don't know what might cause that error and how an application should handle it.
For getting the current UISceneSession I could pass it along into every viewController and view which might need it, but that is cumbersome. This is what I've got instead. It seems odd and fragile. How can I make it more idiomatic?
extension UIApplication {
@discardableResult func closeSceneFor(view: UIView) -> Bool {
if #available(iOS 13.0, *) {
if let window = view.window,
let sceneSession = UIApplication.shared.sceneSessionFor(window: window) {
let options = UIWindowSceneDestructionRequestOptions()
options.windowDismissalAnimation = .standard
// TODO: What might cause an error and how should it be handled?
requestSceneSessionDestruction(sceneSession, options: options, errorHandler: nil)
return true
}
}
return false
}
@available(iOS 13.0, *)
func sceneSessionFor(window: UIWindow) -> UISceneSession? {
for sceneSession in self.openSessions {
if let windowScene = sceneSession.scene as? UIWindowScene {
for sceneWindow in windowScene.windows {
if sceneWindow == window {
return sceneSession
}
}
}
}
return nil
}
}