【问题标题】:How to get the Iphone type from simulator (IOS)如何从模拟器(IOS)中获取 Iphone 类型
【发布时间】:2016-02-03 06:59:48
【问题描述】:

有很多解决方案可以找出应用程序在哪个设备上运行。

iOS: How to determine the current iPhone/device model in Swift?

但是在模拟器中运行,我们只能检测到是模拟器,而不是什么类型的模拟器(iphone5,6,6s等)

我们如何使用模拟器根据设备类型测试不同的逻辑? 或者如何检测代码中模拟了哪个设备?

【问题讨论】:

    标签: ios swift ios-simulator device


    【解决方案1】:

    根据我找到的herehere 的答案,我为您编写了这个 Swift 小函数:

    func getPlatformNSString() {
        #if (arch(i386) || arch(x86_64)) && os(iOS)
            let DEVICE_IS_SIMULATOR = true
        #else
            let DEVICE_IS_SIMULATOR = false
        #endif
    
        var machineSwiftString : String = ""
    
        if DEVICE_IS_SIMULATOR == true
        {
            // this neat trick is found at http://kelan.io/2015/easier-getenv-in-swift/
            if let dir = NSProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
                machineSwiftString = dir
            }
        } else {
            var size : size_t = 0
            sysctlbyname("hw.machine", nil, &size, nil, 0)
            var machine = [CChar](count: Int(size), repeatedValue: 0)
            sysctlbyname("hw.machine", &machine, &size, nil, 0)
            machineSwiftString = String.fromCString(machine)!
        }
    
        print("machine is \(machineSwiftString)")
    }
    

    我得到“iPhone8,2”的结果,它转换为 iPhone 6+,这是我的模拟器设置的。

    There's open source code available that you can use that would convert strings like "iPhone8,2" to the proper iPhone model name.

    如果你想摆脱使用“DEVICE_IS_SIMULATOR”魔法的编译器警告,here's a better solution in the form of a class

    【讨论】:

    • 在较新版本的 swift 中调用是 ProcessInfo.processInfo.environment[…]
    【解决方案2】:

    从 Xcode 9.4.1 开始,NSProcessInfo().environment 现在包含“SIMULATOR_DEVICE_NAME”的键。值看起来像“iPhone 8”。

    【讨论】:

      【解决方案3】:

      您还可以使用我的 BDLocalizedDevicesModels 框架在一行代码中获取名称。 在Github 上查看。

      它适用于 Objective-C 和 Swift,可以帮助您获取真实设备或模拟器的设备名称。

      【讨论】:

        猜你喜欢
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        • 2012-04-27
        • 2014-04-07
        • 2015-12-11
        • 2012-04-09
        • 2011-08-08
        相关资源
        最近更新 更多