0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

foreground通知

Posted at

Swiftでは、1つのファイルに複数のクラスや拡張を記述できますが、基本的な慣習として、1つのファイルには一般的に1つのクラスが記述され、それに関連する拡張が同じファイルに含まれることが多いです。

しかし、CommonViewControllerの通知に関連する処理だけを別のファイルに拡張として記述することもできます。その場合、ファイルを分割することでコードがシンプルになります。

CommonViewController.swift:

import UIKit

class CommonViewController: UIViewController {

    // 通知以外の共通処理をここに記述

}

CommonViewController+Notification.swift:

import UIKit

// MARK: - Notification Handling
extension CommonViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNotificationObservers()
    }

    deinit {
        removeNotificationObservers()
    }

    private func setupNotificationObservers() {
        // 通知の設定
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }

    private func removeNotificationObservers() {
        // オブザーバーの解除
        NotificationCenter.default.removeObserver(self)
    }

    @objc private func appDidEnterForeground() {
        // フォアグラウンドに入った時の共通処理
        print("アプリがフォアグラウンドに入りました")
    }

    @objc private func appDidEnterBackground() {
        // バックグラウンドに入った時の共通処理
        print("アプリがバックグラウンドに入りました")
    }
}

このようにして、通知に関する処理を別ファイルに分離することができます。これにより、コードの見通しが良くなり、保守性が向上します。

またCommonViewControllerを継承した他の画面のViewControllerで、通知の処理を共有することができます。継承によって、CommonViewControllerの通知処理が他の画面にも引き継がれ、フォアグラウンドやバックグラウンドの検知が可能になります。

例えば、以下はCommonViewControllerを継承した別の画面での実装です:

class YourSpecificViewController: CommonViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 画面固有の処理を実装
    }

    // CommonViewControllerの通知処理がここで共有される
}

CommonViewControllerの通知処理はYourSpecificViewControllerでも共有され、YourSpecificViewControllerがフォアグラウンドやバックグラウンドに入ると、CommonViewControllerの通知メソッドも呼ばれます。このように簡単に共通の処理を他の画面で利用できます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?