正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣知道正在运行或正在模拟的特定iphone版本。
编辑:我在问题名称中添加了“以编程方式”这个词。我的问题的要点是能够动态包括/排除代码取决于哪个版本/模拟器正在运行,所以我真的在寻找像一个预处理程序指令,可以为我提供这个信息。
正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣知道正在运行或正在模拟的特定iphone版本。
编辑:我在问题名称中添加了“以编程方式”这个词。我的问题的要点是能够动态包括/排除代码取决于哪个版本/模拟器正在运行,所以我真的在寻找像一个预处理程序指令,可以为我提供这个信息。
当前回答
在Swift的情况下,我们可以实现以下
我们可以创建struct,它允许你创建结构化数据
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
}
其他回答
在Swift的情况下,我们可以实现以下
我们可以创建struct,它允许你创建结构化数据
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
}
最好的方法是:
#if TARGET_IPHONE_SIMULATOR
而不是
#ifdef TARGET_IPHONE_SIMULATOR
因为它总是定义为0或1
更新后的代码:
官方声称这是有效的。
#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
苹果增加了对检查应用程序是针对模拟器的支持,如下:
#if targetEnvironment(simulator)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif
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()
}