MacOS下Swift实现iPhone USB连接检测后执行自定义命令问题
修复方案
问题定位
你写的分支逻辑不生效,基本是以下三个原因之一:
- 事件判断条件写错,大概率你是用打印的
Matched字符串做硬匹配,字符串存在大小写、空格或者隐式换行的匹配失败问题 - IOKit回调默认在后台队列执行,你写的命令如果依赖特定线程/权限,没有做适配就会静默失败
- 执行的外部命令路径、权限配置不对
正确修改位置与代码示例
直接在原有IOKit设备事件的回调函数内做分支处理,判断条件直接和IOKit系统常量绑定,不要用字符串匹配,示例修改如下:
原有回调结构:
func deviceEventCallback(iterator: io_iterator_t, context: UnsafeMutableRawPointer?) { // 原有设备遍历逻辑 let event = getEventString() print("Event \(event)") }
修改后逻辑:
func deviceEventCallback(iterator: io_iterator_t, context: UnsafeMutableRawPointer?) { // 遍历迭代器里的所有设备 while let device = IOIteratorNext(iterator) { // 直接取系统返回的通知类型做判断,避免字符串匹配错误 let eventType = IOIteratorGetNotificationType(iterator) // 设备插入对应kIOFirstMatchNotification if eventType == kIOFirstMatchNotification { // 此处插入你要执行的iPhone信息获取命令 // 示例用Process执行外部shell命令 let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/bin/env") // 替换为你自己的命令参数 task.arguments = ["idevice_id", "-l"] let outputPipe = Pipe() task.standardOutput = outputPipe task.standardError = outputPipe do { try task.run() task.waitUntilExit() let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile() if let result = String(data: outputData, encoding: .utf8) { print("命令执行结果:\(result)") } } catch { print("命令执行失败:\(error)") } } // 设备拔出对应kIOTerminatedNotification else if eventType == kIOTerminatedNotification { print("Event Terminated") } // 释放IOKit设备对象,避免内存泄漏 IOObjectRelease(device) } }
额外注意事项
- 如果你执行的命令需要USB访问权限,需要在Xcode项目的
Signing & Capabilities->Hardened Runtime中勾选USB Access选项 - 执行外部命令时建议写绝对路径,避免环境变量加载失败找不到命令
- 如果需要在命令执行后更新UI,要手动切换到主队列执行UI相关代码
内容的提问来源于stack exchange,提问作者mật khẩu không đổi
相关产品推荐
相关产品推荐

