Swift中HomeKist发现和管理支持HomeKit的配件

Posted hualuoshuijia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift中HomeKist发现和管理支持HomeKit的配件相关的知识,希望对你有一定的参考价值。

如果我们想打开灯,或者别的控件,首先需要找到改控件,根据该控件找到该控件的服务,根据服务找到该控件的特征,根据特征的描述打开或者关闭该灯,这里只写到特征,控制特征参考下一篇

import UIKit
import HomeKit

class ViewController: UIViewController,HMHomeManagerDelegate,HMAccessoryBrowserDelegate{
    
    @IBOutlet weak var tableView: UITableView?
    var manager: HMHomeManager!
    /*HMAccessory控件,具体到冰箱,洗衣机,空调*/
    var accessories = [HMAccessory]()
    /*HMAccessoryBrowser查找控件的类,*/
    lazy var accessoryBrower:HMAccessoryBrowser = {
        let brower = HMAccessoryBrowser()
        brower.delegate = self
        return brower
    }()
    var home:HMHome!
    var room:HMRoom!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.manager = HMHomeManager()
        self.manager?.delegate = self;
    }
    //homekit初始化完毕
    public func homeManagerDidUpdateHomes(_ manager: HMHomeManager){
        home = self.manager.homes[0]
        room = home.rooms[0]
        //开始查找配件,支持HomeKit
        self.accessoryBrower.startSearchingForNewAccessories()
    }
    
    //发现一个新的配件  HMAccessoryBrowserDelegate
    public func accessoryBrowser(_ browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory){
        print("-------------(accessory.name)")
        home.addAccessory(accessory) {[weak self] (error) in
            let strongSelf = self!
            if error == nil{
                print("添加控件成功")
                strongSelf.home.assignAccessory(accessory, to: strongSelf.room, completionHandler: { (error) in
                    if error == nil{
                        print("把控件添加房间成功")
                        strongSelf.findServicesForAccessort(accessory: accessory)
                    }else{
                         print("把控件添加房间失败")
                    }
                })
            }else{
               print("添加控件失败")
            }
        }
        
        
    }
    //移除一个新的配件  HMAccessoryBrowserDelegate
    public func accessoryBrowser(_ browser: HMAccessoryBrowser, didRemoveNewAccessory accessory: HMAccessory){
        
    }
    
    func findServicesForAccessort(accessory:HMAccessory){
        print("发现服务")
        for service in accessory.services as [HMService]{
            print("--------service name:(service.name)  type:(service.serviceType)")
            //找到服务,遍历服务的特征
            findCharacteristicsOfService(service: service)
        }
    }
    func findCharacteristicsOfService(service:HMService){
        for characteristic in service.characteristics as [HMCharacteristic]{
            print("???????????????????? characteristic type:(characteristic.characteristicType)")
        }
    }
}

 

以上是关于Swift中HomeKist发现和管理支持HomeKit的配件的主要内容,如果未能解决你的问题,请参考以下文章

添加对 Swift 包管理器的支持无法正确构建

iOS支持Swift包管理器吗?[已关闭]

支持 swift 3.0 和 iOS 8.0+ 的等效 Alamofire 库

Swift 文件管理框架 FileKit

Swift程序员对Rust印象:内存管理

Swift程序员对Rust印象:内存管理