从 Swift 获取计算机信息
Get computer informations from Swift
使用 Swift 我想获得一个字符串,其中包含有关计算机的指示信息 运行 我的应用程序,例如:
- OS版本
- 机器类型
- 处理器和内存(已安装且免费)
用 Google 搜索了一下,但似乎没有明确的答案。
你一次只能问一个问题,但我会尽量总结一下:
获取操作系统版本
ProcessInfo.processInfo.operatingSystemVersionString
要获得机器类型可没那么容易。您只能获得模型标识符 AFAIK MacPro5,1
。您需要使用终端命令
sysctl hw.model
Processor 我想你也需要终端命令。
sysctl -n machdep.cpu.brand_string
sysctl -n machdep.cpu.core_count
获取物理内存。我不确定你是否也可以获得空闲内存。
ProcessInfo.processInfo.physicalMemory
要在 Swift 中使用终端命令,您可以执行以下操作:
extension DataProtocol {
var string: String? { String(bytes: self, encoding: .utf8) }
}
extension Process {
static func stringFromTerminal(command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.launchPath = "/bin/bash"
task.arguments = ["-c", "sysctl -n " + command]
task.launch()
return pipe.fileHandleForReading.availableData.string ?? ""
}
static let processor = stringFromTerminal(command: "machdep.cpu.brand_string")
static let cores = stringFromTerminal(command: "machdep.cpu.core_count")
static let threads = stringFromTerminal(command: "machdep.cpu.thread_count")
static let vendor = stringFromTerminal(command: "machdep.cpu.vendor")
static let family = stringFromTerminal(command: "machdep.cpu.family")
}
用法:
Process.processor
使用 Swift 我想获得一个字符串,其中包含有关计算机的指示信息 运行 我的应用程序,例如:
- OS版本
- 机器类型
- 处理器和内存(已安装且免费)
用 Google 搜索了一下,但似乎没有明确的答案。
你一次只能问一个问题,但我会尽量总结一下:
获取操作系统版本
ProcessInfo.processInfo.operatingSystemVersionString
要获得机器类型可没那么容易。您只能获得模型标识符 AFAIK
MacPro5,1
。您需要使用终端命令sysctl hw.model
Processor 我想你也需要终端命令。
sysctl -n machdep.cpu.brand_string
sysctl -n machdep.cpu.core_count
获取物理内存。我不确定你是否也可以获得空闲内存。
ProcessInfo.processInfo.physicalMemory
要在 Swift 中使用终端命令,您可以执行以下操作:
extension DataProtocol {
var string: String? { String(bytes: self, encoding: .utf8) }
}
extension Process {
static func stringFromTerminal(command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.launchPath = "/bin/bash"
task.arguments = ["-c", "sysctl -n " + command]
task.launch()
return pipe.fileHandleForReading.availableData.string ?? ""
}
static let processor = stringFromTerminal(command: "machdep.cpu.brand_string")
static let cores = stringFromTerminal(command: "machdep.cpu.core_count")
static let threads = stringFromTerminal(command: "machdep.cpu.thread_count")
static let vendor = stringFromTerminal(command: "machdep.cpu.vendor")
static let family = stringFromTerminal(command: "machdep.cpu.family")
}
用法:
Process.processor