Close the current UISceneSession

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
  }
}

Replies

I found a bit in the WWDC session 212 which answers my first question! There is an API on UIWindow to get the UIWindowScene. This simplifies my example:


extension UIApplication {
  @discardableResult func closeSceneFor(view: UIView) -> Bool {
    if #available(iOS 13.0, *) {
      if let sceneSession = view.window?.windowScene?.session {

        let options = UIWindowSceneDestructionRequestOptions()
        options.windowDismissalAnimation = .standard

        requestSceneSessionDestruction(sceneSession, options: options, errorHandler: nil)
        return true
      }
    }
    return false
  }
}


I am still curious if it is safe to ignore the errorHandler parameter.