У добавленных аксессуаров нет доступных сервисов после добавления сервисов в симулятор HomeKit?

Итак, я пытаюсь написать простое приложение для управления домашними устройствами, но у меня проблемы с кодом.

Вот мой код для просмотра аксессуаров для дома. Но когда я

print(accessory.services.count)

Я получаю 0. Вот часть моего кода:

import UIKit
import HomeKit

class DiscoveryTableViewController: UITableViewController, HMAccessoryBrowserDelegate {

//outlets
@IBAction func backButton(_ sender: AnyObject) {
    navigationController?.dismiss(animated: true, completion: nil)
}

@IBOutlet weak var saveButton: UIBarButtonItem!



let homeManager = HMHomeManager()
let browser = HMAccessoryBrowser()

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

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    //setting the title to "Searching..."
    title = "Searching..."

    //setting the browser delegate = to self
    browser.delegate = self
    //searching for accessories
    browser.startSearchingForNewAccessories()

    //only searching for a short time to be efficient
    Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(DiscoveryTableViewController.stopSearching), userInfo: nil, repeats: false)


}



func stopSearching() {
    title = "Discovered"
    browser.stopSearchingForNewAccessories()
}


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 accessories.count

}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "DiscoveryTableViewCell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! DiscoveryTableViewCell
    let accessory = accessories[(indexPath as NSIndexPath).row] as HMAccessory

    // Configure the cell...
    cell.discNameLabel.text = accessory.name

    //print(accessory.services.count)

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedAcc = accessories[indexPath.row]
    performSegue(withIdentifier: "showDeviceDetail", sender: self)
    //performSegue(withIdentifier: "UnwindToDeviceTable", sender: self)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDeviceDetail" {
        if let destination = segue.destination as? AddDeviceViewController {
            destination.addedAcc = selectedAcc
        }
    }
}


// Informs us when we've located a new accessory in the home
func accessoryBrowser(_ browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory) {
    accessories.append(accessory)

    //PRINTING SERVICES.COUNT
    print(accessory.services.count)
    tableView.reloadData()
}



func accessoryBrowser(_ browser: HMAccessoryBrowser, didRemoveNewAccessory accessory: HMAccessory) {
    var index = 0
    for item in accessories {
        if item.name == accessory.name {
            accessories.remove(at: index)
            break; // done
        }
        index += 1
    }
    tableView.reloadData()
}


}

В этом классе я просматриваю все свои аксессуары. Я могу получить доступ ко всем именам всех устройств, но когда я печатаю «services.count», я каждый раз получаю 0. Кто-нибудь может помочь? И да, я добавил услуги и характеристики под каждый аксессуар в симуляторе HomeKit.


person Jolaroux    schedule 03.10.2016    source источник
comment
Вы уже подключили аксессуар и добавили его в дом? Я без проблем зацикливаю сервисы после сопряжения и добавления аксессуара в дом. Я использую симулятор аксессуаров HomeKit с аксессуарами, которые я создал.   -  person Paul Bonneville    schedule 04.10.2016


Ответы (1)


Я только что подтвердил это, услуги недоступны до тех пор, пока вы не добавите аксессуар в дом, что означает, что вы выполнили сопряжение с аксессуаром:

homeManagerInstance.primaryHome?.addAccessory(accessory, completionHandler: { (error) in
   print("ACCESSORY SERVICES: \(accessory.services.count)")
})

Если вы попытаетесь проверить service.count до этого, он действительно вернется к нулю.

person Paul Bonneville    schedule 04.10.2016
comment
Итак, я вставляю ваш код в свой код, и он запускает процесс сопряжения, где появляется меню, в котором говорится, введите номер сопряжения домашнего комплекта или что-то еще, но затем оно исчезает и говорит, что HomeKit не может соединиться с этим устройством. Вы знаете, что это может быть? Он исчезает до того, как я внесу изменения для ввода кода - person Jolaroux; 04.10.2016
comment
Не уверен, что там происходит, поскольку все эти экраны волшебным образом генерируются и отображаются iOS. Единственная мысль, которая пришла мне в голову, это то, что как только появится этот экран сопряжения, не нажимайте на него. Просто начните вводить код. - person Paul Bonneville; 05.10.2016
comment
Даже когда я ничего не печатаю, экран все равно исчезает через секунду или две. Я тоже запутался :/ Я тоже вставил туда твой код Так что я действительно не знаю, что происходит, ха-ха - person Jolaroux; 05.10.2016
comment
Как вы думаете, я мог видеть фрагменты вашего кода? Достаточно, чтобы увидеть, как вы добавили дом и добавили аксессуар? Было бы удивительно, если бы вы могли - person Jolaroux; 05.10.2016