1

自 iOS9 以来,该identifier属性HMAccessory已贬值。还有另一种方法来比较 HMAccessory 的两个不同实例吗?

4

3 回答 3

4

在 iOS 9 中确定 HMAccessory 的新方法是使用

@available(iOS 9.0, *)
@NSCopying public var uniqueIdentifier: NSUUID { get }
于 2015-12-02T16:54:48.143 回答
0

有几种方法可以做到这一点。正如@Maria 提到的,从iOS9 开始,您拥有NSUUID 属性“uniqueIdentifier”:

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

此外,您可以使用序列号特征类型来比较 HMAccessories,但是请记住:您应该检查配件的“可达性”和“已阻止”状态。如果配件无法访问或被阻止,则您可能无法读取序列号。

最后,我在 Objective C 中包含了一个实用程序代码片段(想要 Swift?只是问问,或者更好的是,将其用作练习;)):

/** @discussion: 如果附件无法访问,则返回空字符串。无法获取处于无法访问状态的实际序列号。* */

[如果您要粘贴此内容,请注明]

+ (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 @"";
}
于 2015-12-03T04:12:00.210 回答
-1

好吧,想出了一个解决方案。有一个HMCharaceteristic HMCharaceteristicTypeSerialNumber。扩展至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
  }
 }
}

现在可以比较:

accessory1.serialNumber == accessory2.serialNumber

还有其他解决方案吗?

于 2015-12-01T21:45:28.693 回答