查询HMHome的房间列表
import UIKit import HomeKit class RoomsVC: UIViewController,UITableViewDataSource,UITableViewDelegate ,HMHomeDelegate{ @IBOutlet weak var tableView: UITableView? var home:HMHome!{ didSet{ home.delegate = self; } } override func viewDidLoad() { super.viewDidLoad() self.title = "rooms" self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(addRooms)) self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } @objc func addRooms(){ let addRoomVC = AddRoomsVC.init(nibName: "AddRoomsVC", bundle: nil) addRoomVC.home = self.home; self.home.delegate = self; self.navigationController?.pushViewController(addRoomVC, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let homeStemp = self.home{ return homeStemp.rooms.count }else{ return 0; } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell let home = self.home.rooms[indexPath.row] 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){ home.removeRoom((home.rooms[indexPath.row]), completionHandler: {[weak self] (Error) in if Error == nil{ self?.tableView?.deleteRows(at: [indexPath], with: .fade) } }) } public func homeDidUpdateName(_ home: HMHome){ self.tableView?.reloadData() } public func home(_ home: HMHome, didAdd room: HMRoom){ self.tableView?.reloadData() } public func home(_ home: HMHome, didRemove room: HMRoom){ self.tableView?.reloadData() } }
//添加房间
import UIKit import HomeKit class AddRoomsVC: UIViewController { @IBOutlet weak var roomNameTF: UITextField! var home:HMHome? override func viewDidLoad() { super.viewDidLoad() } @IBAction func addRoomBtnClick(_ sender: Any) { if (roomNameTF.text?.isEmpty)!{ print("请输入房间名字") return } home?.addRoom(withName: roomNameTF.text!, completionHandler: { (room, error) in if error == nil{ self.navigationController? .popViewController(animated: true) } }) } }