Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect current device using SwiftUI?

Tags:

ios

uikit

swiftui

I am trying to determine whether the device being used is iPhone or iPad.

Please see this question: Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

That solution works if you use UIKit. But

What is the equivalent method if you are using SwiftUI ?

like image 301
Rahul Iyer Avatar asked Apr 09 '20 04:04

Rahul Iyer


People also ask

How do I know if my current device is iPhone or iPad in Swift?

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.

How do I find my current iPhone model?

Getting The Model CodeThe model code is close to the device name, but not exactly. For example an iPhone 11 Pro Max has the model code iPhone12,5 . This will print for example x86_64 if you are using a simulator or iPhone12,5 if you are using a real iPhone 11 Pro Max it will say iPhone12,5 .

Is iPad a SwiftUI?

The Swift Playgrounds iPad app has recently added support for SwiftUI, as well as the Combine framework which provides new ways to handle asynchronous events.


2 Answers

You can find the device type, like this:

if UIDevice.current.userInterfaceIdiom == .pad {
    ...
}
like image 109
workingdog support Ukraine Avatar answered Oct 23 '22 20:10

workingdog support Ukraine


You can use this:

UIDevice.current.localizedModel

In your case, an implementation method could be:

if UIDevice.current.localizedModel == "iPhone" {
     print("This is an iPhone")
} else if UIDevice.current.localizedModel == "iPad" {
     print("This is an iPad")
}

Obviously, you can use this for string interpolation such as this (assuming the current device type is an iPhone):

HStack {
     Text("Device Type: ")
     Text(UIDevice.current.localizedModel)
}

//Output:
//"Device Type: iPhone"

It will return the device type. (iPhone, iPad, AppleWatch) No further imports are necessary aside from SwiftUI which should have already been imported upon creation of your project if you selected SwiftUI as the interface.

NOTE: It does not return the device model (despite the ".localizedModel")

Hope this helps!

like image 41
Alan D. Powell Avatar answered Oct 23 '22 19:10

Alan D. Powell