Skip to content

Retrieves information about the host device πŸ“±

License

Notifications You must be signed in to change notification settings

backslash-f/device

Repository files navigation

swift-version swift-package-manager platforms ci-status license

Device πŸ“±

Retrieves information about the host device, such as its type (iPhone, iPad, TV, watch), OS version, orientation (landscape, portrait), screen size, etc.

Usage Examples

Device's Orientation

(Available in iOS and Mac Catalyst)

let device = Device()

// At any time:
let currentOrientation = device.orientation

// Observe orientation changes:
var cancellables = Set<AnyCancellable>()
device.$orientation
    .sink { orientation in
        switch orientation {
        case .portrait:
            // Do portrait stuff
        case .landscapeRight:
            // Do landscape stuff
        default:
            // Handle .faceDown, .faceUp, .landscapeLeft, .portraitUpsideDown, .unknown, etc
        }
    }
    .store(in: &cancellables)

Device's Operating System

let device = Device()
let os = device.os()

// E.g. running in an iOS device:
let os = device.os()
if os.major >= 14 {
    // Do iOS 14 stuff
}

// E.g. running in a macOS device:
if os.major == 11 && os.minor >= 0 {
    // Do macOS 11.0 stuff
}

// Notice: for any platform, ".minor", ".patch" and ".description" are also available.

Device's Screen Size

(Available in iOS, Mac Catalyst and tvOS)

let device = Device()
let screenSize = device.screenSize

Device's Type

let device = Device()
switch device.type() {
case .iPhone:
    // Do iPhone stuff
case .iPad:
    // Do iPad stuff
case .tv:
    // Do TV stuff
case .mac(isCatalyst: false):
    // Do Mac stuff
case .mac(isCatalyst: true):
    // Do Catalyst stuff
case .watch:
    // Do Watch stuff
case .unknow:
    // Do Unknown stuff
}

Available Properties

Property Description
@Published var orientation: UIDeviceOrientation Subscribe to this variable to keep track of the orientation changes of the device. Available only in iOS and Mac Catalyst, as it relies on the orientationDidChangeNotification notification and the UIDeviceOrientation Enumeration.
public static var screenSize: CGRect Returns the device's screen size in points.

Available APIs

API Description
disableLogging() Disables logging output.
enableLogging() Enables logging output via AppLogger.
os() Returns the operating system version based on -[NSProcessInfo operatingSystemVersionString] and -[NSProcessInfo operatingSystemVersion].
type() Returns the type of the device based on the result of the os() and targetEnvironment() functions.

Integration

Xcode

Use Xcode's built-in support for SPM.

or...

Package.swift

In your Package.swift, add Device as a dependency:

dependencies: [
  .package(url: "https://github.com/backslash-f/device", from: "1.0.0")
],

Associate the dependency with your target:

targets: [
  .target(name: "App", dependencies: ["Device"])
]

Run: swift build