如何以编程方式确定我的应用程序是否在 iPhone 模拟器中运行?

发布于 2024-07-12 06:44:17 字数 166 浏览 10 评论 0原文

正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣了解正在运行或正在模拟的特定 iphone 版本。

编辑:我在问题名称中添加了“以编程方式”一词。 我的问题的重点是能够根据正在运行的版本/模拟器动态包含/排除代码,所以我真的在寻找类似预处理器指令之类的东西,可以为我提供此信息。

As the question states, I would mainly like to know whether or not my code is running in the simulator, but would also be interested in knowing the specific iphone version that is running or being simulated.

EDIT: I added the word 'programmatically' to the question name. The point of my question is to be able to dynamically include / exclude code depending on which version / simulator is running, so I'd really be looking for something like a pre-processor directive that can provide me this info.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

扎心 2024-07-19 06:44:17

已经问过,但标题截然不同。

针对 iPhone 进行编译时 Xcode 设置的#defines

我将重复我的答案:

它位于 SDK 文档中的“有条件编译源代码”下。

相关定义是 TARGET_OS_SIMULATOR,它是在 iOS 框架内的 /usr/include/TargetConditionals.h 中定义的。 在工具链的早期版本中,您必须编写:

#include "TargetConditionals.h"

但在当前(Xcode 6/iOS8)工具链上不再需要这样做。

因此,例如,如果您想检查您是否正在设备上运行,您应该

#if TARGET_OS_SIMULATOR
    // Simulator-specific code
#else
    // Device-specific code
#endif

根据适合您的用例进行操作。

Already asked, but with a very different title.

What #defines are set up by Xcode when compiling for iPhone

I'll repeat my answer from there:

It's in the SDK docs under "Compiling source code conditionally"

The relevant definition is TARGET_OS_SIMULATOR, which is defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:

#include "TargetConditionals.h"

but this is no longer necessary on the current (Xcode 6/iOS8) toolchain.

So, for example, if you want to check that you are running on device, you should do

#if TARGET_OS_SIMULATOR
    // Simulator-specific code
#else
    // Device-specific code
#endif

depending on which is appropriate for your use-case.

愁杀 2024-07-19 06:44:17

更新的代码:

据称这可以正式工作。

#if TARGET_IPHONE_SIMULATOR
NSString *hello = @"Hello, iPhone simulator!";
#elif TARGET_OS_IPHONE
NSString *hello = @"Hello, device!";
#else
NSString *hello = @"Hello, unknown target!";
#endif

原始帖子(已弃用)

此代码将告诉您是否正在模拟器中运行。

#ifdef __i386__
NSLog(@"Running in the simulator");
#else
NSLog(@"Running on a device");
#endif

Updated code:

This is purported to work officially.

#if TARGET_IPHONE_SIMULATOR
NSString *hello = @"Hello, iPhone simulator!";
#elif TARGET_OS_IPHONE
NSString *hello = @"Hello, device!";
#else
NSString *hello = @"Hello, unknown target!";
#endif

Original post (since deprecated)

This code will tell you if you are running in a simulator.

#ifdef __i386__
NSLog(@"Running in the simulator");
#else
NSLog(@"Running on a device");
#endif
孤星 2024-07-19 06:44:17

不是预处理器指令,但这就是我在回答这个问题时所寻找的;

NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
    //device is simulator
}

Not pre-processor directive, but this was what I was looking for when i came to this question;

NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
    //device is simulator
}
匿名。 2024-07-19 06:44:17

Swift 现在有更好的方法。

Xcode 9.3及更新版本,可以使用#if targetEnvironment(simulator)来检查。

#if targetEnvironment(simulator)
//Your simulator code
#endif

There is a better way now in Swift.

As of Xcode 9.3 and newer, you can use #if targetEnvironment(simulator) to check.

#if targetEnvironment(simulator)
//Your simulator code
#endif
谜兔 2024-07-19 06:44:17

最好的方法是:

#if TARGET_IPHONE_SIMULATOR

而不是

#ifdef TARGET_IPHONE_SIMULATOR

因为它总是定义为:0 或 1

The best way to do this is:

#if TARGET_IPHONE_SIMULATOR

and not

#ifdef TARGET_IPHONE_SIMULATOR

since its always defined: 0 or 1

蓝天 2024-07-19 06:44:17

如果是 Swift,我们可以实现以下

我们可以创建结构,允许您创建结构化数据

struct Platform {
    static var isSimulator: Bool {
        #if targetEnvironment(simulator)
            // We're on the simulator
            return true
        #else
            // We're on a device
             return false
        #endif
    }
}

然后如果我们想检测是否正在为 Swift 中的设备或模拟器构建应用程序。

if Platform.isSimulator {
    // Do one thing
} else {
    // Do the other
}

In case of Swift we can implement following

We can create struct which allows you to create a structured data

struct Platform {
    static var isSimulator: Bool {
        #if targetEnvironment(simulator)
            // We're on the simulator
            return true
        #else
            // We're on a device
             return false
        #endif
    }
}

Then If we wanted to Detect if app is being built for device or simulator in Swift then .

if Platform.isSimulator {
    // Do one thing
} else {
    // Do the other
}
一身软味 2024-07-19 06:44:17

适用于 Swift 4.1 及更新版本和 Xcode 9.3 及更高版本

使用此代码:

#if targetEnvironment(simulator)
   // Simulator
#else
   // Device
#endif

Works for Swift 4.1 and newer and Xcode 9.3 and newer

Use this code:

#if targetEnvironment(simulator)
   // Simulator
#else
   // Device
#endif
清泪尽 2024-07-19 06:44:17

所有这些答案都很好,但它在某种程度上让像我这样的新手感到困惑,因为它没有澄清编译检查和运行时检查。 预处理器在编译时之前,但我们应该让它更清楚

这篇博客文章显示如何检测iPhone模拟器?清楚

运行时

首先,我们简单讨论一下。 UIDevice 已经为您提供了有关设备的信息,

[[UIDevice currentDevice] model]

将根据应用程序的运行位置向您返回“iPhone Simulator”或“iPhone”。

编译时间

但是,您想要的是使用编译时间定义。 为什么? 因为您严格编译应用程序以在模拟器内部或设备上运行。 Apple 做了一个名为 TARGET_IPHONE_SIMULATOR 的定义。 那么让我们看一下代码:

#if TARGET_IPHONE_SIMULATOR

NSLog(@"Running in Simulator - no app store or giro");

#endif

All those answer are good, but it somehow confuses newbie like me as it does not clarify compile check and runtime check. Preprocessor are before compile time, but we should make it clearer

This blog article shows How to detect the iPhone simulator? clearly

Runtime

First of all, let’s shortly discuss. UIDevice provides you already information about the device

[[UIDevice currentDevice] model]

will return you “iPhone Simulator” or “iPhone” according to where the app is running.

Compile time

However what you want is to use compile time defines. Why? Because you compile your app strictly to be run either inside the Simulator or on the device. Apple makes a define called TARGET_IPHONE_SIMULATOR. So let’s look at the code :

#if TARGET_IPHONE_SIMULATOR

NSLog(@"Running in Simulator - no app store or giro");

#endif
春庭雪 2024-07-19 06:44:17

对于 Swift 4.2 / Xcode 10

我在 UIDevice 上创建了一个扩展,因此我可以轻松询问模拟器是否正在运行。

// UIDevice+CheckSimulator.swift

import UIKit

extension UIDevice {
    
    /// Checks if the current device that runs the app is xCode's simulator
    static func isSimulator() -> Bool {        
        #if targetEnvironment(simulator)
            return true
        #else
            return false
        #endif
    }
}

例如,在我的 AppDelegate 中,我使用此方法来决定是否需要注册远程通知,这对于模拟器来说是不可能的。

// CHECK FOR REAL DEVICE / OR SIMULATOR
if UIDevice.isSimulator() == false {
        
    // REGISTER FOR SILENT REMOTE NOTIFICATION
    application.registerForRemoteNotifications()
}

For Swift 4.2 / Xcode 10

I created an extension on UIDevice, so I can easily ask for if the simulator is running.

// UIDevice+CheckSimulator.swift

import UIKit

extension UIDevice {
    
    /// Checks if the current device that runs the app is xCode's simulator
    static func isSimulator() -> Bool {        
        #if targetEnvironment(simulator)
            return true
        #else
            return false
        #endif
    }
}

In my AppDelegate for example I use this method to decide wether registering for remote notification is necessary, which is not possible for the simulator.

// CHECK FOR REAL DEVICE / OR SIMULATOR
if UIDevice.isSimulator() == false {
        
    // REGISTER FOR SILENT REMOTE NOTIFICATION
    application.registerForRemoteNotifications()
}
窝囊感情。 2024-07-19 06:44:17

以前的答案有点过时了。 我发现您需要做的就是查询 TARGET_IPHONE_SIMULATOR 宏(不需要包含任何其他头文件 [假设您正在为 iOS 编码])。

我尝试了 TARGET_OS_IPHONE,但在实际设备和模拟器上运行时它返回了相同的值 (1),这就是为什么我建议改用 TARGET_IPHONE_SIMULATOR

The previous answers are a little dated. I found that all you need to do is query the TARGET_IPHONE_SIMULATOR macro (no need to include any other header files [assuming you are coding for iOS]).

I attempted TARGET_OS_IPHONE but it returned the same value (1) when running on an actual device and simulator, that's why I recommend using TARGET_IPHONE_SIMULATOR instead.

云之铃。 2024-07-19 06:44:17

快速:

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

检测应用程序是否正在为 Swift 中的设备或模拟器构建

In swift :

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

From Detect if app is being built for device or simulator in Swift

满身野味 2024-07-19 06:44:17

有没有人考虑过此处提供的答案

我想 Objective-c 的等价物是

+ (BOOL)isSimulator {
    NSOperatingSystemVersion ios9 = {9, 0, 0};
    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
    if ([processInfo isOperatingSystemAtLeastVersion:ios9]) {
        NSDictionary<NSString *, NSString *> *environment = [processInfo environment];
        NSString *simulator = [environment objectForKey:@"SIMULATOR_DEVICE_NAME"];
        return simulator != nil;
    } else {
        UIDevice *currentDevice = [UIDevice currentDevice];
        return ([currentDevice.model rangeOfString:@"Simulator"].location != NSNotFound);
    }
}

Has anyone considered the answer provided here?

I suppose the objective-c equivalent would be

+ (BOOL)isSimulator {
    NSOperatingSystemVersion ios9 = {9, 0, 0};
    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
    if ([processInfo isOperatingSystemAtLeastVersion:ios9]) {
        NSDictionary<NSString *, NSString *> *environment = [processInfo environment];
        NSString *simulator = [environment objectForKey:@"SIMULATOR_DEVICE_NAME"];
        return simulator != nil;
    } else {
        UIDevice *currentDevice = [UIDevice currentDevice];
        return ([currentDevice.model rangeOfString:@"Simulator"].location != NSNotFound);
    }
}
人生戏 2024-07-19 06:44:17

我遇到了同样的问题,TARGET_IPHONE_SIMULATORTARGET_OS_IPHONE 始终被定义,并设置为 1。皮特的解决方案当然有效,但如果你碰巧在某些东西上构建除了英特尔(不太可能,但谁知道),只要 iphone 硬件不改变,这里有一些东西是安全的(所以你的代码将始终适用于当前的 iphone):

#if defined __arm__ || defined __thumb__
#undef TARGET_IPHONE_SIMULATOR
#define TARGET_OS_IPHONE
#else
#define TARGET_IPHONE_SIMULATOR 1
#undef TARGET_OS_IPHONE
#endif

将其放在方便的地方,然后假装TARGET_* 常量定义正确。

I had the same problem, both TARGET_IPHONE_SIMULATOR and TARGET_OS_IPHONE are always defined, and are set to 1. Pete's solution works, of course, but if you ever happen to build on something other than intel (unlikely, but who knows), here's something that's safe as long as the iphone hardware doesn't change (so your code will always work for the iphones currently out there):

#if defined __arm__ || defined __thumb__
#undef TARGET_IPHONE_SIMULATOR
#define TARGET_OS_IPHONE
#else
#define TARGET_IPHONE_SIMULATOR 1
#undef TARGET_OS_IPHONE
#endif

Put that somewhere convenient, and then pretend that the TARGET_* constants were defined correctly.

爱*していゐ 2024-07-19 06:44:17

包括所有类型的“模拟器”

NSString *model = [[UIDevice currentDevice] model];
if([model rangeOfString:@"Simulator" options:NSCaseInsensitiveSearch].location !=NSNotFound)
{
    // we are running in a simulator
}

To include all types of "simulators"

NSString *model = [[UIDevice currentDevice] model];
if([model rangeOfString:@"Simulator" options:NSCaseInsensitiveSearch].location !=NSNotFound)
{
    // we are running in a simulator
}
﹏雨一样淡蓝的深情 2024-07-19 06:44:17

如果没有效果,试试这个

public struct Platform {

    public static var isSimulator: Bool {
        return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
    }

}

if nothing worked, try this

public struct Platform {

    public static var isSimulator: Bool {
        return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
    }

}
送君千里 2024-07-19 06:44:17

使用 Swift 4.2 (Xcode 10),我们可以做到这一点

#if targetEnvironment(simulator)
  //simulator code
#else 
  #warning("Not compiling for simulator")
#endif

With Swift 4.2 (Xcode 10), we can do this

#if targetEnvironment(simulator)
  //simulator code
#else 
  #warning("Not compiling for simulator")
#endif
浮萍、无处依 2024-07-19 06:44:17

我的回答基于@Daniel Magnusson 的回答以及@Nuthatch 和@n.Drake 的评论。 我编写它是为了为使用 iOS9 及更高版本的 swift 用户节省一些时间。

这对我有用:

if UIDevice.currentDevice().name.hasSuffix("Simulator"){
    //Code executing on Simulator
} else{
    //Code executing on Device
}

My answer is based on @Daniel Magnusson answer and comments of @Nuthatch and @n.Drake. and I write it to save some time for swift users working on iOS9 and onwards.

This is what worked for me:

if UIDevice.currentDevice().name.hasSuffix("Simulator"){
    //Code executing on Simulator
} else{
    //Code executing on Device
}
明月夜 2024-07-19 06:44:17

/// 如果是模拟器而不是设备则返回 true

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #endif
}

/// Returns true if its simulator and not a device

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #endif
}
往事随风而去 2024-07-19 06:44:17

Apple 添加了对检查应用程序是否针对模拟器的支持,具体如下:

#if targetEnvironment(simulator)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif

Apple has added support for checking the app is targeted for the simulator with the following:

#if targetEnvironment(simulator)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif
那片花海 2024-07-19 06:44:17

这对我最有效

NSString *name = [[UIDevice currentDevice] name];


if ([name isEqualToString:@"iPhone Simulator"]) {

}

This worked for me best

NSString *name = [[UIDevice currentDevice] name];


if ([name isEqualToString:@"iPhone Simulator"]) {

}
没有伤那来痛 2024-07-19 06:44:17

在我看来,答案(上面给出并在下面重复):

NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
    //device is simulator
}

是最好的答案,因为它显然是在运行时执行的,而不是作为编译指令执行的。

In my opinion, the answer (presented above and repeated below):

NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
    //device is simulator
}

is the best answer because it is obviously executed at RUNTIME versus being a COMPILE DIRECTIVE.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文