1 // Copyright 2021-present 650 Industries. All rights reserved.
2 
3 import ExpoModulesCore
4 
5 public final class KeepAwakeModule: Module {
6   private var activeTags = Set<String>()
7 
8   public func definition() -> ModuleDefinition {
9     Name("ExpoKeepAwake")
10 
11     AsyncFunction("activate", activate)
12     AsyncFunction("deactivate", deactivate)
13     AsyncFunction("isActivated", isActivated)
14 
15     OnAppEntersForeground {
16       if !self.activeTags.isEmpty {
17         setActivated(true)
18       }
19     }
20     OnAppEntersBackground {
21       if !self.activeTags.isEmpty {
22         setActivated(false)
23       }
24     }
25   }
26 
27   private func activate(tag: String) -> Bool {
28     if activeTags.isEmpty {
29       setActivated(true)
30     }
31     activeTags.insert(tag)
32     return true
33   }
34 
35   private func deactivate(tag: String) -> Bool {
36     activeTags.remove(tag)
37     if activeTags.isEmpty {
38       setActivated(false)
39     }
40     return true
41   }
42 }
43 
44 private func isActivated() -> Bool {
45   return DispatchQueue.main.sync {
46     return UIApplication.shared.isIdleTimerDisabled
47   }
48 }
49 
50 private func setActivated(_ activated: Bool) {
51   DispatchQueue.main.async {
52     UIApplication.shared.isIdleTimerDisabled = activated
53   }
54 }
55