LoginSignup
0
1

More than 3 years have passed since last update.

iPadOSでの現在表示しているSceneの取得方法

Last updated at Posted at 2019-11-01

iOS,Android開発初心者です.Qiita投稿もほぼ初心者なので間違っていたら色々指摘していただけると幸いです.

iPadOS13よりUIScene APIが導入されました.UIApplicationでは1つのウィンドウのみを考えて開発してたのに対し,UISceneにより複数ウィンドウを管理できるようになりました.そこでSceneごとに変数を設定したいと思ったら意外にもハマってしまったのでここで共有します.

今までの異なるView Controller間の変数の共有方法

いくつか方法があるそうですが,初心者向けのサイトなどで紹介されている方法としてはAppDelegate.swiftに変数を宣言.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var hogehoge: String = "hogehoge"

そして使いたいView Controllerで以下のように取得できる.

let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let hogehoge = appDelegate.hogehoge

しかしながらこの方法ではすべてのマルチウィンドウで同じ変数を共有してしまう.
またこの方法以外にもシングルトンを使う方法などがあるがシングルトンもマルチウィンドウで同じ変数を共有してしまう.そのためシングルトンなどを今まで使っていた人はUISceneSession#persistentIdentifierで対応する必要がある.(https://qiita.com/snoozelag/items/fe95df7e748ad5fc3205 参照)

マルチウィンドウにおける異なるView Controller間同士の変数の共有方法

まずいままでと同じようにSceneDelegate.swiftに変数を宣言.

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    var hogehoge: string = "hogehoge"

そして使いたいView Controllerで以下のように取得可能.

let scene:UIScene! = UIApplication.shared.connectedScenes.filter{
      $0.session.configuration.storyboard == self.storyboard
}.first
let sceneDelegate:SceneDelegate! = scene.delegate as? SceneDelegate
let hogehoge = sceneDelegate.hogehoge

UIApplication.shared.connectedScenesはマルチウィンドウに表示しているすべてのSceneを取得してしまう.そこで現在表示しているstoryboardが$0.session.configuration.storyboardと等しいことを確認することで取得可能になる.
他にいい方法とかあれば教えてほしい....

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1