From a8706b57d989ed6b4e85f83264424e413727ad20 Mon Sep 17 00:00:00 2001 From: Rakuyo Date: Sun, 21 Apr 2024 16:48:44 +0800 Subject: [PATCH] feat: Supports obtaining the identifier of the corresponding device under the simulator --- CHANGELOG.md | 4 ++ Sources/Core/Utilities/Device.swift | 57 ++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b1053f..2b213f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to this project are documented in this file. ## [Unreleased](https://github.com/RakuyoKit/RakuyoKit/compare/1.0.4...HEAD) +### Changed + +- `Device.codeName` supports obtaining the real device identification corresponding to the current simulator. [#10](https://github.com/RakuyoKit/RakuyoKit/pull/10) @rakuyoMo + ----- ## [1.0.4 - Format and Lint](https://github.com/RakuyoKit/RakuyoKit/releases/tag/1.0.4) (2024-4-21) diff --git a/Sources/Core/Utilities/Device.swift b/Sources/Core/Utilities/Device.swift index 4998d39..e2e6679 100644 --- a/Sources/Core/Utilities/Device.swift +++ b/Sources/Core/Utilities/Device.swift @@ -8,23 +8,70 @@ import UIKit +// MARK: - Device + public enum Device { + public static func generateUUID() -> String { + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + } +} + +// MARK: - Code Name + +extension Device { + public enum Running { + case realMachine + case simulator + case wherever + } + /// Device model code /// /// like iPhone1,1 public static var codeName: String { + codeName(running: .wherever) + } + + /// When running on a real machine in the physical world, + /// the identifier corresponding to the device is returned. + /// + /// like `iPhone1,1` + private static var realMachineCodeName: String { var info = utsname() uname(&info) - + let machineMirror = Mirror(reflecting: info.machine) - + return machineMirror.children.reduce(into: "") { guard let value = $1.value as? Int8, value != 0 else { return } $0 += String(UnicodeScalar(UInt8(value))) } } - - public static func generateUUID() -> String { - UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + + /// When the simulator is running, the identifier of + /// the real device corresponding to the simulator is returned. + private static var simulatorCodeName: String? { + ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] + } + + /// Device model code + /// + /// like iPhone1,1 + public static func codeName(running: Running) -> String { + switch running { + case .realMachine: + return realMachineCodeName + + case .simulator: + if let _codeName = simulatorCodeName { return _codeName } + assertionFailure( + "Please call this property when the simulator is running." + + " Consider using `#if targetEnvironment(simulator)` to isolate your code." + ) + return realMachineCodeName + + case .wherever: + return simulatorCodeName ?? realMachineCodeName + } } }