Search code examples
iosobjective-chomekitios-homekit

HMAccessoryDelegates not calling on Button action


I am working on Homekit iOS app. I have a question that I have an accessory and When I change its power characteristic value using the HomeKit Simulator the delegates of HMAccessory are caliing but in case If I change the powr characteristic value programmatically (Using the writevalue ) the delegate methods are not being called. Please let me know any ideas of suggestions.

Code 

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    selectedDevice.delegate = self;
}

HMAccessoryDelegate

- (void)accessory:(HMAccessory *)accessory service:(HMService *)service didUpdateValueForCharacteristic:(HMCharacteristic *)characteristic;
{
    NSLog(@"changed");
}

Write Function

UISwitch *sw = [[UISwitch alloc] initWithFrame:CGRectMake(230, 5, 51, 31)];
[cell addSubview:sw];
sw.on = YES;
[sw addTarget:self action:@selector(updateState:) forControlEvents:UIControlEventValueChanged];

-(void)updateState:(UISwitch*)sender
{
HMCharacteristic *characteristic = self.selectedService.characteristics[tag];

[characteristic enableNotification:YES completionHandler:^(NSError *error)
             {
                 if(!error)
                 {

                 }
             }];
 if([characteristic.characteristicType isEqualToString:HMCharacteristicTypePowerState])
        {
        id val = characteristic.value;
        NSString *str = [NSString stringWithFormat:@"%@",val];

        if([str isEqualToString:@"0"])
        {
            id a = characteristic.value;

            BOOL b = [a boolValue];

            NSNumber *c = [NSNumber numberWithBool:!b];

            AppDelegate *appDel = [[UIApplication sharedApplication] delegate];

            [characteristic writeValue:c completionHandler:^(NSError *error) {
                if (error) {
                    UIAlertView *alertController = [[UIAlertView alloc] initWithTitle:@"Error" message:[appDel handleErrorCodes:error.code] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alertController show];
                    return;
                }
                else
                {
                    [serviceCharacteristicsTableView reloadData];
                }
            }];

        }
}

Please let me know if I am not clear


Solution

  • The documentation says that the delegate method is not called when you set the value programatically:

    This method is called as a result of a change in value initiated by the accessory. Programmatic changes initiated by the app do not result in this method being called.

    If you want to do something after writing the characteristic's value succeeded (or failed), you can do it in the completionHandler: block of writeValue:completionHandler: method.