TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Have app prevent computer going to sleep

Forums > macOS


I'm developing a macOS SwiftUI app that is listening for events of a smart home device on the local network using server-sent events (SSE). The problem is that the computer goes to sleep once the user leaves it, and then my app is also put to sleep/suspended (unsure about the correct terminology here)

The whole point is to catch the events and analyze them for the user over time, for example over night. The events are triggered by the device using SSE, hence there is no polling or similar the app can do to catch up. It needs to continue listen over the network.

How do I achieve this?

(technically it should be possible, as there are apps like Caffeinated, Owly and Amphetamine. Not to mention that while you watch a movie then the laptop is not going to sleep)

I've search and found some examples, but I haven't managed to get any of them work and they seem quite outdated (or I just don't understand how to get them to work with a Swift/SwiftUI app)

Thanks in advance!



Well, I guess it is the implicit rubberducking of putting down the problem in a message 🙂 - I got a solution working that I just verified by having the app running overnight.

// NoSleep.swift

import Foundation
import IOKit.pwr_mgt

struct NoSleep {
    private static var assertionID: IOPMAssertionID = 0
    private static var success: IOReturn?

    static func disableSleep() -> Bool? {
         guard success == nil else { return nil }
         success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString,
                                                "String with reason for preventing sleep" as CFString,
                                                &assertionID )
         return success == kIOReturnSuccess

    static func enableSleep() -> Bool {
        if success != nil {
            success = IOPMAssertionRelease(assertionID)
            success = nil
            return true
        return false

I invoke this in .onAppear() in the main content view using NoSleep.disableSleep().

Worth noting, the application does not show up in Activity Monitor under the Energy tab (where the Preventing Sleep column is), which I expected it to.


Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.