How to Get Iobluetoothdevice's Battery Level, Using Swift and Appkit (Xcode for MACos)

How can I get IOBluetoothDevice's battery level, using Swift and AppKit (Xcode for MacOS)

You can get the battery level of Bluetooth devices from the IORegistry with IOKit.

This is a simple example to get the battery level for the Magic Trackpad 2

import IOKit

var serialPortIterator = io_iterator_t()
var object : io_object_t
let port: mach_port_t
if #available(macOS 12.0, *) {
port = kIOMainPortDefault // New name in macOS 12 and higher
} else {
port = kIOMasterPortDefault // Old name in macOS 11 and lower
}
let matchingDict : CFDictionary = IOServiceMatching("AppleDeviceManagementHIDEventService")
let kernResult = IOServiceGetMatchingServices(port, matchingDict, &serialPortIterator)

if KERN_SUCCESS == kernResult {
repeat {
object = IOIteratorNext(serialPortIterator)
if object != 0, let percent = IORegistryEntryCreateCFProperty(object, "BatteryPercent" as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as? Int {
print(percent)
break
}
} while object != 0
IOObjectRelease(object)
}
IOObjectRelease(serialPortIterator)

For other devices you have to replace AppleDeviceManagementHIDEventService and Trackpad2 with the appropriate values. You can display the entire IORegistry in Terminal.app with ioreg -l.

How to code datasource for a NSComboBoxCell with in a Tableview for a macOS program using Xcode 12?

Objective-C

- (NSInteger)numberOfItemsInComboBoxCell:(NSComboBoxCell *)comboBoxCell;

is in Swift

optional func numberOfItems(in comboBoxCell: NSComboBoxCell) -> Int

Source: numberOfItemsInComboBoxCell

Is IBDesignable broken for AppKit in Xcode 9.2 and Swift 4?

I was able to get this to work in the latest Xcode by adding the following two lines to the top of the initialControlSetup function:

wantsLayer = true
canDrawSubviewsIntoLayer = true

I think this basically tells the NSView to render in a way that is more similar to how iOS works. If this worked in Xcode 8.3 as you say, it's possible that Apple introduced this regression in Xcode 9 without realizing it.



Related Topics



Leave a reply



Submit