Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine device type from Swift? (OS X or iOS)

Tags:

macos

ios

swift

I know Swift is relatively new, but I was wondering if there was a way to determine the device type?

(Like you used to be able to do with a #define)?

Mainly I would like to know how to differentiate OS X or iOS. I have found nothing on the subject.

like image 960
user1947561 Avatar asked Jun 05 '14 16:06

user1947561


People also ask

How do I know if my iPhone is swift or iPad?

To detect current device with iOS/Swift we can use UserInterfaceIdiom. It is an enum in swift, which tells which device is being used. The interface idiom provides multiple values in it's enum which are. When we run the above code on an iPhone device following is the result produced.

How do I find my iOS device name?

Open the Settings app to check your iOS information: Tap General. Tap About. It will show the device info, including the device name.

What version of iOS do I have?

Go to your iPad or iPhone's home screen, then touch the "Settings" icon. From there, select "General." Next, tap "About." You'll see all of the information about your device, including the version of your iOS device.

What is device make?

When we talk about the device make, we refer to the Phone manufacturer (e.g. Apple, Samsung, Nokia and so on) and device model is generally the specific product such as iPhone, iPad/TAB etc. Any mobile devices will be categorized using make and model only.


1 Answers

If you're building for both iOS and macOS (and maybe for watchOS and tvOS, too), you're compiling at least twice: once for each platform. If you want different code to execute on each platform, you want a build-time conditional, not a run-time check.

Swift has no preprocessor, but it does have conditional build directives — and for the most part, they look like the C equivalent.

#if os(iOS) || os(watchOS) || os(tvOS)     let color = UIColor.red #elseif os(macOS)     let color = NSColor.red #else     println("OMG, it's that mythical new Apple product!!!") #endif 

You can also use build configurations to test for architecture (x86_64, arm, arm64, i386), Target environment (iOS simulator or Mac Catalyst), or -D compiler flags (including the DEBUG flag defined by the standard Xcode templates). Don’t assume that these things go together — Apple has announced macOS on arm64 to ship in 2020, so arm64 doesn’t imply iOS, and iOS Simulator doesn’t imply x86, etc.

See Compiler Control statements in The Swift Programming Language.

(If you want to distinguish which kind of iOS device you're on at runtime, use the UIDevice class just like you would from ObjC. It's typically more useful and safe to look at the device attributes that are important to you rather than a device name or idiom — e.g. use traits and size classes to lay out your UI, check Metal for the GPU capabilities you require, etc.)

like image 95
rickster Avatar answered Sep 30 '22 14:09

rickster