(Swift HomeKit) Сопряжение аксессуаров домашнего набора, но экран ввода «Setup Code» исчезает до того, как я смогу ввести код

#ios #swift #homekit

#iOS #swift #homekit

Вопрос:

Я пишу простое приложение для управления освещением моего домашнего комплекта. В моем коде я пытаюсь добавить выбранное устройство в свой дом, и это несколько работает. Однако в моем приложении, когда появляется экран, на котором я ввожу «Setup Code», он исчезает через 1-2 секунды и сообщает «Home не удалось выполнить сопряжение с этим аксессуаром», прежде чем я получу возможность ввести код настройки полностью.

Вот мой код.

 import UIKit
import HomeKit

class HomeTestTableViewController: UITableViewController {


let homeManager = HMHomeManager()
var activeHome: HMHome?
var activeRoom: HMRoom?


var devices = [HMAccessory]()
var selectedAcc: HMAccessory?

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return devices.count
    //devices[0].services.
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Configure the cell...
    let cellIdentifier = "HomeTableViewCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! HomeTableViewCell
    cell.deviceName.text = devices[indexPath.row].name

    //setting button
    //let deviceSwitch = UISwitch(frame: CGRect.zero) as UISwitch



    return cell
}

@IBAction func unwindToDeviceTable(_ sender: UIStoryboardSegue) {

    if let sourceViewController = sender.source as? AddDeviceViewController, let device = sourceViewController.addedAcc{

        homeManager.primaryHome?.addAccessory(device, completionHandler: { (error) in
            print("ACCESSORY SERVICES: (device.services.count)")
        })

        let newIndexPath = IndexPath(row: devices.count, section: 0)
        devices.append(device)
        tableView.insertRows(at: [newIndexPath], with: .bottom)
        tableView.reloadData()
    }
}


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedAcc = devices[indexPath.row]
    //print(selectedAcc?.services.count)
    performSegue(withIdentifier: "viewDeviceDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "viewDeviceDetail" {
        if let destination = segue.destination as? ShowDeviceViewController {
            destination.showSelectedDevice = selectedAcc 

        }
    }
}
}
  

В моей функции перехода «UnwindToDeviceTable» это когда я пытаюсь сохранить аксессуар с другого контроллера просмотра, который выбирает аксессуар. Это работает, но я не знаю, почему экран setup code исчезает так быстро. Кто-нибудь может помочь?
Спасибо!

Комментарии:

1. кажется вероятным, что объект device освобождается до того, как вы получите возможность ответить на диалоговое окно.

2. Я тоже об этом думаю, знаете ли вы, как бы я это исправил?

3. Либо это, либо я неправильно добавляю home, поэтому он запускает настройку, а затем завершается сбоем