Swift: How to check if your app is running on a Device or a Simulator ?

Sometimes you need to check if the app is running on a device or a simulator. Why? If you’re using GoogleMobileAds lib you may need to verify is you’re on simulator to show the testing ads provided by Google.

Bildschirmfoto 2017-09-22 um 15.48.38

Happily there’s a way to do it. I personally prefer creating a struct, since I don’t need a class for it.

So let’s get started:

struct Platform {

    static let isSimulator: Bool = {

        var isSim = false

        #if arch(i386) || arch(x86_64)

          isSim = true

        #endif

        return isSim

    }()

}

 

What does the code do ? It basically checks if the architecture is i386 or x86_64 which means a computer.(Simulator)

The arch(i386) build configuration returns true when code is compiled for the 32–bit iOS simulator.

Then you can use it on your code:

   if(Platform.isSimulator){

    //your code goes here

  }

Acknowledgment

Thanks for reading this post, it is always a pleasure writing for you guys. If you like what you just read and somehow you want to support me, you can become a Patreon . Being my Patreon makes you get my private posts about programming with iOS and Ruby.

If you’d like to know more about me or what I do, you can follow me on Instagram or Twitter .

See you next time!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s