1

I've just approached Swift, for building a quick utility app for my MacBook. I have written the following code, but it gives me the error "Cannot find 'UIScreen' in scope".

class AppDelegate: NSObject,NSApplicationDelegate{
    //...
    func applicationDidFinishLaunching(_ notification: Notification) {

        Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
            UIScreen.mainScreen().brightness = CGFloat(0.0) //<- error here
        }
    }
    //...
}

Initially I thought I've missed an import, but I cannot find what to import (UIKit, is only for iOS). Thank you for any help

1 Answers1

3

Anything beginning with "UI" is an iOS class. Those classes are not available from a macOS app.

The equivalent class for macOS is probably NSScreen, although I don't think it has an exposed brightness property like the one you are trying to set.

Edit:

It looks like it is possible to set the screen brightness in MacOS, but you have to use much lower-level code. Check out this link.

The relevant code from that link is the following, which uses IOKit:

func setBrightnessLevel(level: Float) {

    var iterator: io_iterator_t = 0

    if IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &iterator) == kIOReturnSuccess {

        var service: io_object_t = 1

        while service != 0 {

            service = IOIteratorNext(iterator)
            IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey, level)
            IOObjectRelease(service)

        }

    }
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272