LoginSignup
25
20

More than 5 years have passed since last update.

[Swift3.0]iOS・tvOSアプリを実行中に画面ロック(スリープ)しないようにする方法

Last updated at Posted at 2016-11-09

画面ロックしてほしくないこともある

iOS版の浮世絵時計アプリを開発しているときに見つけた小ネタです。

浮世絵時計アプリは、iPhoneやiPadを時計代わりにするので、自動的に画面ロック(スリープ)してほしくありません。そこで、自動画面ロックを解除する方法を探して、見つけたのが下記のコードです。

UIApplication.shared.isIdleTimerDisabled = true

isIdleTimerDisabledプロパティ(初期値はfalse)にtrueを代入することで、スリープ状態へ移行する時間を監視しているIdleTimerをオフにすることができます。

このコードを、画面ロックを解除したい箇所で実行します。
例えば、ある画面だけロックしないようにする場合は、その画面(ViewController)のviewDidLoadで実行します。

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.isIdleTimerDisabled = true
    }

アプリケーションを起動したときに適用したい場合は、下記のようにAppDelegateに書いてしまってもいいかもしれません。

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UIApplication.shared.isIdleTimerDisabled = true

        return true
    }

注意点

isIdleTimerDisabledのリファレンスを読むと、下記のような注意点が記載されています。

Important
You should set this property only if necessary and should be sure to reset it to false when the need no longer exists. Most apps should let the system turn off the screen when the idle timer elapses. This includes audio apps. With appropriate use of Audio Session Services, playback and recording proceed uninterrupted when the screen turns off. The only apps that should disable the idle timer are mapping apps, games, or programs where the app needs to continue displaying content when user interaction is minimal.

画面ロックを解除すると、画面がつきっぱなしになるので、バッテリーを消耗してしまいます。ユーザーのバッテリーを無駄にしないためにも、処理が終わったらすぐに画面ロックを元に戻すのをお忘れなく。

浮世絵時計アプリでは、viewDidDisappearで元に戻すようにしました。

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        UIApplication.shared.isIdleTimerDisabled = false
    }

追記

tvOS版の浮世絵時計アプリにも、isIdleTimerDisabledを組み込んで動作確認しました。

Apple TVは、操作なしで一定時間経過→スクリーンセーバー表示→スリープという段階を踏みますが、isIdleTimerDisabled = trueの場合は、スクリーンセーバーも表示されなくなりました。

浮世絵時計アプリのように、コンテンツを流しておくアプリを開発する場合は、ぜひお試しください。

25
20
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
25
20