Skip to content

Commit

Permalink
Merge pull request #10 from RakuyoKit/feature/emulator-code-name-mapping
Browse files Browse the repository at this point in the history
Supports obtaining the identifier of the corresponding device under the simulator
  • Loading branch information
rakuyoMo authored Apr 21, 2024
2 parents 5e5c235 + a8706b5 commit e26f0df
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
57 changes: 52 additions & 5 deletions Sources/Core/Utilities/Device.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}

0 comments on commit e26f0df

Please sign in to comment.