Rahul Iyer
Rahul Iyer

Reputation: 21025

How to detect current device using 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 ?

Upvotes: 21

Views: 16105

Answers (3)

oskarko
oskarko

Reputation: 4178

UIDevice is no longer available from WatchKit 2 on

WKInterfaceDevice could be helpful: https://developer.apple.com/documentation/watchkit/wkinterfacedevice

i.e.:

let systemName = WKInterfaceDevice.current().systemName
let systemVersion = WKInterfaceDevice.current().systemVersion
let deviceModel = WKInterfaceDevice.current().model

Upvotes: 0

You can find the device type, like this:

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

Upvotes: 30

Alan D. Powell
Alan D. Powell

Reputation: 81

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!

Upvotes: 7

Related Questions