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
Use Multiple Codingkeys for a Single Property
Swift/Firebase - Sort Posts in Tableview by Date
Swift UI MACos Background Transparent Textfield
How to Send Push Notifications Without Using Firebase Console
Swiftui Present Alert with Input Field
How to Trigger an Action When a Swiftui Toggle() Is Toggled
Init an Object Conforming to Codable with a Dictionary/Array
Nsmanagedobject Changes Do Not Trigger Objectwillchange
Why Does Swiftui Uihostingcontroller Have Extra Spacing
Retrieve Multiple Photos Under a Node from Firebase Storage
Swift Maximum Consecutive Positive Numbers
Swiftui Out of Index When Deleting an Array Element in Foreach
Why Is the Alert Triggering Out of Order If Value Is Not Updated
How to Convert Anyclass to a Specific Class and Init It Dynamically in Swift