title: Stopping Mac from sleeping while app is running
body: <p>I want to stop a the user's Macbook from automatically sleeping while one the app is running. How would I do that? I have seen this </p>
  
  <p><a href="https://developer.apple.com/library/content/qa/qa1340/_index.html" rel="nofollow noreferrer">https://developer.apple.com/library/content/qa/qa1340/_index.html</a></p>
  
  <p>and this: </p>
  
  <p><a href="https://stackoverflow.com/questions/36757229/disable-sleep-mode-in-os-x-with-swift">Disable sleep mode in OS X with swift</a></p>
  
  <p>and this: </p>
  
  <p><a href="https://stackoverflow.com/questions/37601453/using-swift-to-disable-sleep-screen-saver-for-osx/46519646#46519646">Using Swift to disable sleep/screen saver for OSX</a></p>
  
  <p>But there is no simple line of code that I can put or a delegate method that makes this simple like there is in iOS? I just want to have the entire app work properly and stop the computer from automatically going to sleep. If someone puts in it to sleep manually, then obviously that is fine. I don't want to prevent the user from putting the computer to sleep. But as long as my app is running I don't want the computer to sleep. Like when you are watching a movie, the app does not go to sleep. How do I do that?</p>
  
  <p>I feel like this is the code that I need but do I just run this function in the viewdidload and it will work? Is it that simple?</p>
  
  <pre><code>var assertionID: IOPMAssertionID = 0
  var success: IOReturn?
  
  func disableScreenSleep(reason: String = "Unknown reason") -&gt; Bool? {
      guard success != nil else { return nil }
      success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString,
                                         IOPMAssertionLevel(kIOPMAssertionLevelOn),
                                         reason as CFString,
                                         &amp;assertionID )
      return success == kIOReturnSuccess
  }
  </code></pre>