问题
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
:
How to determine the Apple Watch model?
Could anyone help me figure out why this function isn't working? It sometimes returns
"Watc\t"
instead of the expected
"Watch2,4"
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
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"
回答1:
You never allocate a buffer to receive the machine string. Change
var machine = CChar()
to
var machine = [CChar](repeating: 0, count: size)
and you should be good to go!
来源:https://stackoverflow.com/questions/64455391/capture-model-identifier-for-apple-watch-from-watchos