How to Check if You're Running on the Simulator in Swift
I haven't posted in a while but here's a quick Swift snippet just so this site doesn't become completely stale.
I spend a lot of my time developing iOS apps that work with our web applications. When I run the app in the simulator I want it to talk to the copy of that web application that's running on my development machine and when I run it on a device (or issue a beta build) it should talk to the staging server. In Objective C this was easy. I'd just use TARGET_IPHONE_SIMULATOR
to switch between hosts. Unfortunately, This doesn't work as well in Swift.
If you Google it you'll find this thread on Stack Overflow and this code in particular:
#if (arch(i386) || arch(x86_64)) && os(iOS)
...
#endif
From here I ended up with this code:
#if (arch(i386) || arch(x86_64)) && os(iOS)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif
This would build and run fine from Xcode but the first time I tried to archive the target for release it would complain that DEVICE_IS_SIMULATOR
was undefined.
After some experimentation I came up with the following code that seems to work well:
struct Platform {
static let isSimulator: Bool = {
var isSim = false
#if arch(i386) || arch(x86_64)
isSim = true
#endif
return isSim
}()
}
// Elsewhere...
if Platform.isSimulator {
// Do one thing
}
else {
// Do the other
}
I hope this helps someone. Let me know if you have a better way. I'm off to go grill some burgers.