Easy way to detect iOS device properties, OS versions and work with screen sizes. Powered by Swift.

Overview

AssistantKit

CI Status Version License Platform

Easy way to detect device environment:

Helps to:

Installation

AssistantKit is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "AssistantKit"

Usage

Device version information

To get the current device type, use:

let device = Device.type

switch device {
case .phone:      print("iPhone")
case .pad:        print("iPad")
case .pod:        print("iPod")
case .simulator:  print("Simulator")
default:          print("Unknown")
}

You can check the exact device version with next code. All possible values of version can be found in the Version enum, located in the Version.swift file.

switch Device.version {
case .phone5C:      print("iPhone 5C")
case .phone6:       print("iPhone 6")
case .phone6S:      print("iPhone 6S")
case .phone6Plus:   print("iPhone 6 Plus")
case .phone6SPlus:  print("iPhone 6 S Plus")
// and more iPhones

case .padAir:       print("iPad Air")
case .padAir2:      print("iPad Air 2")
case .padMini:      print("iPad Mini")
case .padPro:       print("iPad Pro")
// and more iPads

case .podTouch6:    print("iPod 6")
// and more iPods

case .simulator:    print("Simulator")
default:            print("Unknown device")
}

There are few properties that detect device type

Device.isPhone     // true for iPhones even if it's Simulator
Device.isPad       // true for iPads even if it's Simulator
Device.isPadPro    // true for iPad Pros even if it's Simulator
Device.isPod       // true for iPods
Device.isSimulator // true for Simulators
Device.isNotched   // true for newer device version with notch

To get raw device code use

Device.versionCode

Device screen parameters

Detecting screen size can be detected with next code. All possible values could be found in the Screen enum, located in Screen.swift.

switch Device.screen {
case .inches_4_7:  print("4.7 inches")
case .inches_5_5:  print("5.5 inches")
case .inches_7_9:  print("7.9 inches")
case .inches_9_7:  print("9.7 inches")
case .inches_12_9: print("12.9 inches")
default:           print("Other display")
}

Compare screens

Screen is cinfirming to Comparable protocol:

Screen.inches_3_5 < Screen.inches_4_0 // Will be `true`

Detecting screen family

Often it is required to assign different parameters based on specific screen resolution. There are 3 methods that will help you to detect what parameters to use. But first of all let me introduce ScreenFamily.

This is enum that breaks all possible screens into 3 groups:

  • .old: Reproduce old iPhones with 3.5 and 4.0 inches screens
  • .small: Other iPhones/iPods without iPhone 6 Plus
  • .medium: iPhone 6 Plus and iPad Mini
  • .big: iPad and iPad Pro

You can detect screen family by:

let family = Device.screen.family

And now back to methods:

Value by device type

To assign different values for iPhone and iPad devices you can use:

// Method definition
static public func size<T: Any>(phone phone: T, pad: T) -> T

// Usage example
let size = Device.size(phone: 13, pad: 15)
let font = UIFont(name: "Arial", size: CGFloat(size))

On iPhones your font size will be 13.0, on iPads 15.0

Value by ScreenFamily

Another method based on ScreenFamily:

// Method definition
static public func size<T: Any>(small small: T, medium: T, big: T) -> T

// Usage example
let otherSize = Device.size(small: 12, medium: 14, big: 15)
let otherFont = UIFont(name: "Arial", size: CGFloat(otherSize))

In this case for small screens your font will be 12.0, for medium 14.0 and for big 15.0 inches.

Important notice: By default if screen family can not be detected size method will assign small value.

Value by exact screen size

Also you can return value for specific screen size. There is another size method you can use. Incoming parameter should be a screen size. If it is not defined nearest value will be used. Code example:

// Method definition
static public func size<T: Any>(sizes sizes: [Screen : T]) -> T?

// Usage example
let sizes: [Screen: AnyObject] = [
   .inches_3_5: 12,
   .inches_4_0: 13,
   .inches_4_7: 14,
   .inches_9_7: 15
  ]
let exactSize = Device.size(sizes: sizes) as! Int
let _ = UIFont(name: "Arial", size: CGFloat(exactSize))

Important notice: This method can return nil if you pass an empty array as a parameter. Be careful with implicit unwrapping.

After that your font will be:

  • 12 for 3.5" inches (older devices)
  • 13 for iPhone 5, 5S
  • 14 for iPhone 6, 6Plus and iPad mini
  • and 15 for other iPads

Screen scale

switch Device.scale {
case .x1: print("Not retina")
case .x2: print("Retina 2X")
case .x3: print("Retina 3X")
default:  print("Unknown scale")
}

Also there is a property to detect if it's retina display:

Device.isRetina // true if device screen scale > 1.0

Interface orientation

There are two properties that will help you to know current orientation:

Device.isLandscape // true if landscape
Device.isPortrait  // true if portrait

Slide Over / Multitasking layout for iPad

To detect slide over layout on iPads just call:

Device.isSlideOverLayout // true if iPad is in multitasking / slide over layout

Detecting and comparing iOS version

You can detect iOS version in runtime. There are next different methods that will help you to do it:

Device.osVersion                               // Current version as a `OSVersion` model

Device.osVersion == Device.os12                // true if iOS 12.0
Device.osVersion >= Device.os9                 // true if iOS >= 9.0
Device.osVersion < Device.os11                 // true if iOS < 11.0
etc.

There are next constants representating Main iOS versions:

Device.os8
Device.os9
Device.os10
Device.os11
Device.os12

Working with directories

There are few helper methods to make access to Documents and Caches directoies easier. Take a look at code examples:

Bundle.documentsDirectoryURL           // URL to .DocumentDirectory
Bundle.documentsDirectoryPath          // Path to .DocumentDirectory
Bundle.cachesDirectoryURL              // URL to .CachesDirectory
Bundle.cachesDirectoryPath             // Path to .CachesDirectory

let filePath = "directory/filename.txt"
Bundle.filePathInDocumentsDirectory(toFile: filePath)  // Path to file in .DocumentDirectory
Bundle.filePathInCachesDirectory(toFile: filePath)     // Path to file in .CachesDirectory

Environment

Used to detect environment options. Right now there is only one property:

/// Return `true` if running unit tests
Environment.isRunningUnitTests

Battery

There is a way to get battery state and level with these methods. It will enable monitoring if it's not enabled yet.

Device.Battery.state // Represent `UIDeviceBatteryState`
Device.Battery.level // in range 0...1 -1 for simulators

TODO

  • Add tvOS support

Write me or make a pull request if you have any ideas what else functionality can be useful in this repo.

Author

More Device-detecting libs

License

AssistantKit is available under the MIT license. See the LICENSE file for more info.

Comments
  • Swift 3 and SwiftPM support

    Swift 3 and SwiftPM support

    opened by TofPlay 4
  • Swift4.2

    Swift4.2

    This PR migrates the codebase to Swift 4.2

    I used the native migration tool to convert all the syntax to 4.2. I then took the additional step of changing the build setting SWIFT_SWIFT3_OBJC_INFERENCE to Default, as Apple's migration guide mentions.

    Beyond this work, there were two other files that I added to .git_ignore, as they were at least showing up to me as untracked. I also changed other build settings to the recommended settings, according to Xcode warnings.

    opened by plflanagan 1
  • Support for iPhone XS, XS Max and XR, updates and fixes

    Support for iPhone XS, XS Max and XR, updates and fixes

    • Added iOS 12
    • Added new screen sizes
    • Fixed comparison with unknown. If any of the values of the comparison is unknow, the result is always false.
    • Added iPhone XS, iPhone XS Max and iPhone XR
    • Simplified execution of property type of the Device
    • Added isNotched that returns if the device has a notch or not
    • Removed some default cases for switchs so when adding a new case it is easier to find where to make changes
    • Version based on version code for iPhone XS, iPhone XS Max and iPhone XR
    opened by felipowsky 1
  • Implement some detection for iPad Slide Over / Split View

    Implement some detection for iPad Slide Over / Split View

    Hi, It would be nice if we could have some quick detections in cases when app is running in iPad Slide Over / Split View mode with different screen bounds being applied to it at runtime.

    Best regards

    opened by ElectroBuddha 1
  • iPhone9,3 is unknown.  Crash in

    iPhone9,3 is unknown. Crash in "osVersion"

    Just installed AssistantKit and it looks very interesting. My iPhone 7 isn't detected, so I've created a pull request here: https://github.com/anatoliyv/AssistantKit/pull/7

    Also, osVersion crashes because of Float(UIDevice.current.systemVersion)!. UIDevice.current.systemVersion returns 10.3.1 which can't be converted. I don't know what the best way to handle that is.

    opened by timothycosta 1
  • Comparable Enum Screen

    Comparable Enum Screen

    Hey.

    Thanks a lot for this awesome framework.

    I added Comparable protocol to the enum Screen in order to do things like:

    if Device.screen <= .inches_4_7 {
      // do something for all screen sizes equal or lower than 4.7 inches. 
      // example: all iPods, iPhone 4, 4s, 5, 5c, 5s, 6, 6s, 7, etc.
    }
    

    Also, I added screen property in Version to achieve things like:

    if Device.screen < Version.phone5.screen {
      // do something for all screen sizes lower than iPhone 5.
      // example: iPhone 4, 4s, etc.
    }
    

    Or just:

    if Device.screen < Version.phone5 {
      // same as before
    }
    

    What do you think?

    opened by felipowsky 1
  • Carthage support

    Carthage support

    opened by TofPlay 1
  • Devices with screen 5.5 inch have isNotched true

    Devices with screen 5.5 inch have isNotched true

    Devices with case .phone6Plus, .phone6SPlus, .phone7Plus, .phone8Plus: return .inches_5_5

    Don't have notch and they are in the static public var isNotched: Bool check

    opened by prisacariugeorge 1
Releases(0.3)
  • 0.3(Oct 3, 2017)

  • 0.2(Sep 20, 2017)

    New features:

    • Device Battery support added
    • Environment struct added to provide different env variables
    • Screen and Version Comparable protocol implementation
    • Crash with osVersion: Float fixed
    Source code(tar.gz)
    Source code(zip)
Owner
Anatoliy Voropay
Swifter :]
Anatoliy Voropay
Versions tracker for your iOS, macOS, and tvOS app

VersionTrackerSwift VersionTrackerSwift is a versions / builds tracker to know which version has been installed by a user. Usage In your ApplicationDe

Tom Baranes 82 Oct 5, 2022
Minecraft-silicon - Generate Apple Silicon-native versions of Minecraft

Minecraft Silicon A dead simple utility to generate Apple Silicon-native Minecra

Cole Feuer 4 Jun 21, 2022
A simple utility allowing to detect Swift version at runtime.

SwiftVersionDetector SwiftVersionDetector allows you to detect Swift version at runtime. Note that detecting the Swift version of the machine on which

Alessandro Venturini 2 Dec 3, 2022
I needed to detect idle mode on a SwiftUI app for a kiosk, so I did it.

Inactivity I needed to detect idle mode on a SwiftUI app for a kiosk, so I did it. Usage Important: You must set the Principal class of your app to In

Helio Tejedor 16 Dec 19, 2022
How Swift standard types and classes were supposed to work.

How Swift standard types and classes were supposed to work. A collection of useful extensions for the Swift Standard Library, Foundation, and UIKit.

Goktug Yilmaz 3k Dec 22, 2022
A command-line tool and Swift Package for generating class diagrams powered by PlantUML

SwiftPlantUML Generate UML class diagrams from swift code with this Command Line Interface (CLI) and Swift Package. Use one or more Swift files as inp

null 374 Jan 3, 2023
🕸️ Swift Concurrency-powered crawler engine on top of Actomaton.

??️ ActoCrawler ActoCrawler is a Swift Concurrency-powered crawler engine on top of Actomaton, with flexible customizability to create various HTML sc

Actomaton 18 Oct 17, 2022
Extensions that allow you to work with optionals

RxOptionals Sometimes it happens that you need to bind to several optional binders or to an optional method (for example, when using weak). To do this

Dane4ka 3 Aug 9, 2021
BudouX: the machine learning powered line break organizer tool

BudouX.swift BudouX Swift implementation. BudouX is the machine learning powered

griffin-stewie 39 Dec 31, 2022
A graphical Mach-O viewer for macOS. Powered by Mach-O Kit.

Mach-O Explorer is a graphical Mach-O viewer for macOS. It aims to provide an interface and feature set that are similar to the venerable MachOView ap

Devin 581 Dec 31, 2022
DeviceGuru is a simple lib (Swift) to know the exact type of the device

DeviceGuru DeviceGuru is a simple lib (Swift) to know the exact type of the device, e.g. iPhone 6 or iPhone 6s Easy to use Light weight From version 5

Inder Kumar 442 Dec 28, 2022
Testable Combine Publishers - An easy, declarative way to unit test Combine Publishers in Swift

Testable Combine Publishers An easy, declarative way to unit test Combine Publishers in Swift About Combine Publishers are notoriously verbose to unit

Albert Bori 6 Sep 26, 2022
iOS ReplayKit Screen Share Broadcast Extension Frame Sharing

An iOS app that demonstrates how we can share CMSampleBuffer frames from SampleHandler of Broadcast Extension to the host app and how to pass callbacks to and fro from host app to SampleHandler and vice versa.

IOTric 5 Oct 15, 2022
Passing data from a couple of screen into a Model

Passing-Data Passing data from a couple of screen into a Model Introduction Hi, this video is just a representation project from this Video by Essenti

null 0 Oct 12, 2021
Acknowledgements screen displaying a list of licenses, for example from CocoaPods dependencies.

VTAcknowledgementsViewController Acknowledgements screen displaying a list of licenses, for example from CocoaPods dependencies. Also available in Swi

Vincent Tourraine 868 Oct 28, 2022
A way to easily add Cocoapod licenses and App Version to your iOS App using the Settings Bundle

EasyAbout Requirements: cocoapods version 1.4.0 or above. Why you should use Well, it is always nice to give credit to the ones who helped you ?? Bonu

João Mourato 54 Apr 6, 2022
Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

Apple 833 Jan 3, 2023
XCMetrics is the easiest way to collect Xcode build metrics and improve developer productivity.

XCMetrics is the easiest way to collect Xcode builds metrics and improve your developer productivity. Overview ?? Keep your build times under control

Spotify 989 Jan 2, 2023
A declarative, thread safe, and reentrant way to define code that should only execute at most once over the lifetime of an object.

SwiftRunOnce SwiftRunOnce allows a developer to mark a block of logic as "one-time" code – code that will execute at most once over the lifetime of an

Thumbtack 8 Aug 17, 2022