質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

5310閲覧

swiftでアプリのバックグラウンド状態を検知して処理したい

seastar

総合スコア62

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

1グッド

0クリップ

投稿2021/02/16 21:15

swiftでアプリのバックグラウンド状態を検知して処理したいです。
コードは以下サイト参考にして作成しましたが、作成したコードにブレークポイントを置いても素通りされ、処理が実行できずに悩んでいます。
http://mzgkworks.hateblo.jp/entry/nsnotificationcenter-viewcontroller

初歩的な質問で申し訳ありませんが、知恵をお貸し下さい。

swift

1AppDelegate:ここでバックグラウンド、フォアグラウンドを検知して飛ばす 2class AppDelegate: UIResponder, UIApplicationDelegate { 3 4 var window: UIWindow? 5 func applicationDidEnterBackground(_ application: UIApplication) { 6 // アプリがバックグラウンドへ移行するタイミングを通知 7 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "applicationDidEnterBackground"), object: nil) 8 } 9 10 func applicationWillEnterForeground(_ application: UIApplication) { 11 // アプリがフォアグラウンドへ移行するタイミングを通知 12 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "applicationWillEnterForeground"), object: nil) 13 }

swift

1ViewController:受け取った通知をここで実行? 2 override func viewWillAppear(_ animated: Bool) { 3 super.viewWillAppear(animated) 4 // 登録 5 NotificationCenter.default.addObserver(self, selector: Selector(("viewWillEnterForeground:")), name: NSNotification.Name(rawValue: "applicationWillEnterForeground"), object: nil) 6 NotificationCenter.default.addObserver(self, selector: Selector(("viewDidEnterBackground:")), name: NSNotification.Name(rawValue: "applicationDidEnterBackground"), object: nil) 7 } 8 9 // AppDelegate -> applicationWillEnterForegroundの通知 10 func viewWillEnterForeground(notification: NSNotification?) { 11 textFrontLabel.text = "フォアグラウンド" 12 } 13 14 // AppDelegate -> applicationDidEnterBackgroundの通知 15 func viewDidEnterBackground(notification: NSNotification?) { 16 textBackLabel.text = "バックグラウンド" 17 }
sekiseki_2👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

参考にされている記事の情報をみると

Xcode 6.3.2
Swift 1.2

と相当古い環境の情報ですが、Swift5 あたりで Scene Delegate を使っているのであれば、

Swift

1import UIKit 2 3class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 let notificationCenter = NotificationCenter.default 8 notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil) 9 10 notificationCenter.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil) 11 } 12 13 @objc func appMovedToBackground() { 14 print("App moved to background!") 15 } 16 17 @objc func appMovedToForeground() { 18 print("App moved to foreground!") 19 } 20}

のような感じで Foreground, Background の検出ができると思います。

あるいは、AppDelegate.swift ではなく、SceneDelegate.swift の下記のメソッド

Swift

1 2 func sceneWillResignActive(_ scene: UIScene) { 3 // Called when the scene will move from an active state to an inactive state. 4 // This may occur due to temporary interruptions (ex. an incoming phone call). 5 }

を必要に応じて書き換えることになると思います。

SceneDelegate を使わないのであれば、AppDelegate.swift に

Swift

1 func applicationWillResignActive(_ application: UIApplication) { 2 3 }

を追加して処理を記述することになりますが、公式マニュアル

Tells the delegate that the app is about to become inactive.

Important

If you're using scenes (see Scenes), UIKit will not call this method. Use sceneWillResignActive(_:) instead to pause any activity or save state. UIKit posts a willResignActiveNotification regardless of whether your app uses scenes.

と記述しある通り、Scene Delegate を使うとこのメソッドは呼び出されませんのでご注意ください。

投稿2021/02/16 23:57

TsukubaDepot

総合スコア5086

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2021/02/17 01:04

付け加えると、質問者さんが参考にした記事にはいくつか問題がありまして、 ・参考にした記事では独自の Notification を作って、それを AppDelegate で post してますが、iOS にはシステム定義の Notification があり、それを使えば自動的に通知されるので、わざわざ AppDelegate または SceneDelegate で post する必要はありません。 ・参考にした記事では viewWillAppear で addObserver してますが、その場合 viewDidDisappear あたりで removeObserver すべきでは (そうしないと画面を切り替えて戻ってきた場合に通知が複数回届く可能性が)。  この回答のように viewDidLoad で addObserver する場合は、ViewController が破棄される時に自動的に remove されるので removeObserver は不要です。 ・なお、viewDidLoad と viewWillAppear のどちらで addObserver すべきか (あるいは、AppDelegate や SceneDelegate で処理すべきか) は、やりたい処理によります。
TsukubaDepot

2021/02/17 02:45

hoshi-takanoriさん いつもコメントありがとうございます。 指摘された内容まで考えが及んでいませんでした。 私としても勉強になりました。ありがとうございます。
seastar

2021/02/17 13:14

TsukubaDepotさん、ありがとうございます。 すごく簡単に検知することができました。助かりました。 hoshi-takanoriさん、解説ありがとうございます。無駄なことしているのがよく分かりました。 1つ追加で教えていただいてもいいでしょうか。 ホームボタンで閉じた時にAの処理、アプリを開いたまま電源を閉じた時にBの処理と分けることができません。 調べましたが該当するものがなく、どちらもバックグラウンド扱いになります。 アプリのライフサイクルなどで分ける方法ご存知でしたら、ご教示お願いします。
TsukubaDepot

2021/02/17 15:32

この値は hoshi-takanoriさんの方が遥かに詳しいのでご登場をお待ちするしかありませんが、公式ドキュメントをみている限り、明確に判断する方法はないかもしれません。 https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle ただ、ドキュメントをみた限りないだけであって、実際は実装可能かもしれませんので、ドキュメントを頼りにあらゆる Notification の通知を実験してみる価値はあるかもしれません。
seastar

2021/02/17 21:21

TsukubaDepotさん、ありがとうございます。 公式ドキュメント以外でリンク先のライフサイクル見てました。公式ドキュメント分かり難いイメージで避けてましたが、便利ですね。これから公式ドキュメント確認するようにします。 回答がつくまで、色々試そうと思います。
hoshi-takanori

2021/02/18 00:07

自分もそんなに詳しいわけではありませんが、とりあえず何をしたいかによるでしょうね。 Managing Your App's Life Cycle のドキュメントにも、applicationProtectedDataDidBecomeAvailable(_:) と applicationProtectedDataWillBecomeUnavailable(_:) のリンクがあって、端末がロック・アンロックされた時に呼ばれることになってますけど、これらはあくまでデータ保護のために使うべきとされてます。 https://developer.apple.com/forums/thread/70079
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問