问题描述
看起来似乎没有任何官方记录的从手表应用程序获取 Apple Watch 模型的方法,但是这篇文章展示了 sysctlbyname
的特殊用途:
It looks like there aren't any documented official methods of obtaining the Apple Watch model from a watch app, but there is this post showing special use of sysctlbyname
:
谁能帮我弄清楚为什么这个功能不起作用?它有时会返回
Could anyone help me figure out why this function isn't working? It sometimes returns
手表\t"
而不是预期
Watch2,4"
Swift 的 sysctlbyname 函数似乎就是这里描述的这个 c 函数:https://opensource.apple.com/source/Libc/Libc-167/gen.subproj/sysctlbyname.c.auto.html
Swift's sysctlbyname function seems to be this c function described here:https://opensource.apple.com/source/Libc/Libc-167/gen.subproj/sysctlbyname.c.auto.html
我的代码是从 SO 帖子中的 swift answer 复制而来的:
My code is copied from the swift answer in the SO post:
private func getWatchModel() -> String? {
var size: size_t = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = CChar()
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: &machine, encoding: String.Encoding.utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
} // Should return a string like "Watch2,4"
推荐答案
你从不分配缓冲区来接收机器字符串.改变
You never allocate a buffer to receive the machine string.Change
var machine = CChar()
到
var machine = [CChar](repeating: 0, count: size)
你应该没事了!
这篇关于从 WatchOS 捕获 Apple Watch 的型号标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!