Giải pháp đơn giản
Thêm 1 dòng code vào viewDidLoad của ViewController:
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.isIdleTimerDisabled = true
}
Giải thích
isIdleTimerDisabled = true: Vô hiệu hóa timer ngủ tự động của hệ thống.- Màn hình sẽ **không bao giờ tắt** do ngủ (idle) khi app đang chạy foreground.
- Áp dụng cho toàn bộ app (không chỉ view controller hiện tại).
Lưu ý quan trọng
- Tốn pin đáng kể - chỉ bật khi thực sự cần (navigation, đọc sách, game, call video...).
- Nhớ **bật lại** khi không cần:
UIApplication.shared.isIdleTimerDisabled = false(trongviewWillDisappearhoặcdeinit). - Không hoạt động trên background - iOS sẽ tắt màn hình bình thường khi app vào background.
Best Practice
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.isIdleTimerDisabled = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.isIdleTimerDisabled = false
}
Cách này đảm bảo màn hình chỉ sáng khi view controller này hiển thị.