Capture model identifier for Apple Watch from WatchOS

谁说胖子不能爱 提交于 2021-02-11 12:36:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!