- 第一步:打开HomeKit的功能
- 第二步:plist文件设置权限,String类型,随便写点什么
Privacy - HomeKit Usage Description
- 第三步:获取房间列表,这里用的是个tableView接收的,应该大家都能看的懂,tableView的第一次reload必须在HomeKit初始化完成的时候,也就是代理方式homeManagerDidUpdateHomes之中
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate ,HMHomeManagerDelegate{ @IBOutlet weak var tableView: UITableView? lazy var manager: HMHomeManager = { let manager = HMHomeManager() manager.delegate = self return manager }() override func viewDidLoad() { super.viewDidLoad() self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return manager.homes.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell let home = manager.homes[indexPath.row] as HMHome cell.textLabel?.text = home.name return cell; } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { var arr = [UITableViewRowAction]() let action:UITableViewRowAction = UITableViewRowAction.init( style: .default, title: "删除") {[weak self] (UITableViewRowAction, IndexPath) in self? .deleRoomFromIndex(IndexPath) } arr.append(action) return arr } func deleRoomFromIndex(_ indexPath:IndexPath){ manager.removeHome(manager.homes[indexPath.row]) {[weak self] (Error) in if Error == nil{ self?.tableView?.deleteRows(at: [indexPath], with: .fade) } } } @IBAction func addBtnClick(_ sender: Any) { let vc = AddHomeVC.init(nibName: "AddHomeVC", bundle: nil) self.navigationController?.pushViewController(vc, animated: true) } // HMHomeManagerDelegate Homekit完成初始化会调用这个,所有在初始化完成之后刷新UI public func homeManagerDidUpdateHomes(_ manager: HMHomeManager){ self.tableView?.reloadData() } //添加 public func homeManager(_ manager: HMHomeManager, didAdd home: HMHome){ self.tableView?.reloadData() } //删除 public func homeManager(_ manager: HMHomeManager, didRemove home: HMHome){ self.tableView?.reloadData() } }
- 添加房间
class AddHomeVC: UIViewController { let manager = HMHomeManager() @IBOutlet weak var homeNameTF: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func addHomeBtnClick(_ sender: Any) { if (homeNameTF.text?.isEmpty)!{ print("请输入房间名字") return } manager.addHome(withName: homeNameTF.text!) { (home, error) in if error == nil{ self.navigationController? .popViewController(animated: true) } } } deinit { print("这里销毁了") } }