How to compare instances of HMAccessory

445 Views Asked by At

Since iOS9 the identifier property of HMAccessory has beed depreciated. Is there another way to compare two different instances of HMAccessory?

3

There are 3 best solutions below

1
Maria On BEST ANSWER

The new way to determine the HMAccessory in iOS 9 is by using the

@available(iOS 9.0, *)
@NSCopying public var uniqueIdentifier: NSUUID { get }
1
Christian R On

Alright came up with one solution. There is a HMCharaceteristic HMCharaceteristicTypeSerialNumber. Made an extension to HMAccessory:

extension HMAccessory {
 var serialNumber: String? {
  get {
   for service in services {
    for characteristic in service.characteristics {
     if characteristic.characteristicType == HMCharacteristicTypeSerialNumber {
      return characteristic.value as? String
     }
    }
   }
   return nil
  }
 }
}

Can now compare:

accessory1.serialNumber == accessory2.serialNumber

Any other solutions?

1
John Doe On

There are several ways to do this. As @Maria mentioned, from iOS9 onwards, you have the NSUUID property 'uniqueIdentifier':

@property(readonly, copy, nonatomic) NSUUID *uniqueIdentifier NS_AVAILABLE_IOS(9_0);

Also, you can utilize the serialNumber characteristicType to compare HMAccessories, however, keep in mind: you should check for accessories' 'reachability' and 'blocked' status. If the accessories are unreachable or is blocked, then you may not be able to read serial number.

Lastly, I've included a utility code snippet in Objective C (want Swift? just ask, or better yet, use it as an exercise ;)):

/** @discussion: Returns empty string if accessory is unreachable. Cannot fetch the actual serial number in unreachable state.* */

[Please cite if you are pasting this]

+ (NSString *)getSerialNumberFromHMAccessory:(HMAccessory *)accessory {
    if (!accessory || !accessory.reachable || accessory.isBlocked) {
        return @"";
    }

    for (HMService *service in accessory.services) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@", @"characteristicType", HMCharacteristicTypeSerialNumber];
        NSArray *result = [service.characteristics filteredArrayUsingPredicate:predicate];

        if (result && [result count] > 0 && [result[0] isKindOfClass:[HMCharacteristic class]]) {
            HMCharacteristic *serialNumChar = (HMCharacteristic *)result[0];
            NSString *serialNum = [serialNumChar valueForKey:@"value"];
            if (serialNum && [serialNum length] > 0) {
                //DDLogInfo(@"Found serial number: %@ for accessory named \"%@\"", serialNum, accessory.name);
                return serialNum;
            }
        }
    }

    return @"";
}