How to detect current device using SwiftUI?

Viewed 7859
3 Answers

You can find the device type, like this:

if UIDevice.current.userInterfaceIdiom == .pad {
    ...
}

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!

Related