Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách ngăn iOS Device tự động ngủ (sleep mode) khi app chạy

Mặc định iOS tắt màn hình (sleep) sau một thời gian không tương tác để tiết kiệm pin. Một số app cần giữ màn hình sáng: navigation, đọc sách, video call, kiosk...

Cách 1: Cài đặt hệ thống (User tự bật)

Cài đặt → Màn hình & Độ sáng → Tự động khóa → Không bao giờ

Cách ngăn iOS Device tự động ngủ (sleep mode) khi app chạy

Áp dụng toàn hệ thống, không cần code.

Cách 2: Code trong App (Programmatically)

Sử dụng UIApplication.shared.isIdleTimerDisabled:


import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Ngăn sleep khi view controller này đang hiển thị
        UIApplication.shared.isIdleTimerDisabled = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // QUAN TRỌNG: Bật lại idle timer khi rời màn hình
        UIApplication.shared.isIdleTimerDisabled = false
    }
    
    deinit {
        UIApplication.shared.isIdleTimerDisabled = false
    }
}

Apple Docs: isIdleTimerDisabled

Best Practices

  • Nếu app background, idle timer vẫn hoạt động bình thường
  • Nguyên tắc Lý do
    Chỉ bật khi thực sự cần Tiêu tốn pin, làm nóng thiết bị
    Luôn tắt khi view disappear/deinit Tránh quên tắt → pin hao hết khi user dùng app khác
    Kết hợp với background task
    Thông báo cho user Toast "Màn hình sẽ không tự tắt" khi bật

    Pattern phổ biến: Wrapper class

    
    class IdleTimerManager {
        static let shared = IdleTimerManager()
        private var disabledCount = 0
        
        func disableIdleTimer() {
            disabledCount += 1
            if disabledCount == 1 {
                UIApplication.shared.isIdleTimerDisabled = true
            }
        }
        
        func enableIdleTimer() {
            disabledCount = max(0, disabledCount - 1)
            if disabledCount == 0 {
                UIApplication.shared.isIdleTimerDisabled = false
            }
        }
    }
    
    // Usage trong ViewController
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        IdleTimerManager.shared.disableIdleTimer()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IdleTimerManager.shared.enableIdleTimer()
    }
    

    Lưu ý

    • Property này reset khi app terminate - không persist
    • Không hoạt động nếu Low Power Mode đang bật (iOS ưu tiên tiết kiệm pin)
    • CarPlay / External Display: Idle timer behavior khác biệt
    • App Store Review: Không bị reject nếu dùng đúng mục đích (navigation, video, kiosk)