iosswiftios-darkmodemapbox-ios

Swift: If traitCollection.userInterfaceStyle == .unspecified, how do I determine if it's in light or dark mode?


In the settings of my app, the user can choose between 3 system themes: light, dark, or default (which matches the phone's theme).

I do this by finding the keyWindow and setting overrideUserInterfaceStyle = .dark for dark mode, overrideUserInterfaceStyle = .light for light mode, and overrideUserInterfaceStyle = .unspecified for default.

The problem I'm having is I'm using MapBox within my app and I have both a darkStyleURL and a lightStyleURL. When the user chooses a theme I update the style url as follows:

self.styleURL = self.traitCollection.userInterfaceStyle == .dark ? URL(string: darkStyleURL) : URL(string: lightStyleURL)

But the problem with doing it this way is if the user chooses default as the theme, the traitCollection.userInterfaceStyle is going to be equal to .unspecified. So when the code above triggers, it'll use the lightStyleURL EVEN IF the user's device is in dark mode.

So my question is, after setting overrideUserInterfaceStyle = .unspecified is there another way to determine the user's device theme?

Or is there a better way of handling the use case of matching the device theme or switching between all three options? Any help will be greatly appreciated. Thanks!


Solution

  • You can use UIScreen.main.traitCollection.userInterfaceStyle to get the current device theme independent of the overridden appearance on the window.