草庐IT

ios - NSNetService dictionaryFromTXTRecord 对无效输入的断言失败

coder 2023-09-09 原文

dictionary(fromTXTRecord:) 的输入来自网络,可能来自应用程序外部,甚至是设备。然而,Apple 的 docs 说:

... Fails an assertion if txtData cannot be represented as an NSDictionary object.

断言失败会使程序员(我)无法处理错误,这对于处理外部数据的方法来说似乎不合逻辑。

如果我在 Mac 上的终端中运行它:

dns-sd -R 'My Service Name' _myservice._tcp local 4567 asdf asdf

我的应用在 iPhone 上运行时崩溃了。

dictionary(fromTXTRecord:) 期望 TXT 记录数据 (asdf asdf) 为 key=val 形式。如果像上面一样,一个单词不包含任何 =,该方法将无法解析它并使断言失败。

除了根本不使用该方法并实现我自己的解析之外,我看不出有什么办法可以解决这个问题,这感觉不对。

我错过了什么吗?

最佳答案

这是 Swift 4.2 中的一个解决方案,假设 TXT 记录只有字符串:

/// Decode the TXT record as a string dictionary, or [:] if the data is malformed
public func dictionary(fromTXTRecord txtData: Data) -> [String: String] {

    var result = [String: String]()
    var data = txtData

    while !data.isEmpty {
        // The first byte of each record is its length, so prefix that much data
        let recordLength = Int(data.removeFirst())
        guard data.count >= recordLength else { return [:] }
        let recordData = data[..<(data.startIndex + recordLength)]
        data = data.dropFirst(recordLength)

        guard let record = String(bytes: recordData, encoding: .utf8) else { return [:] }
        // The format of the entry is "key=value"
        // (According to the reference implementation, = is optional if there is no value,
        // and any equals signs after the first are part of the value.)
        // `ommittingEmptySubsequences` is necessary otherwise an empty string will crash the next line
        let keyValue = record.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
        let key = String(keyValue[0])
        // If there's no value, make the value the empty string
        switch keyValue.count {
        case 1:
            result[key] = ""
        case 2:
            result[key] = String(keyValue[1])
        default:
            fatalError()
        }
    }

    return result
}

关于ios - NSNetService dictionaryFromTXTRecord 对无效输入的断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193911/

有关ios - NSNetService dictionaryFromTXTRecord 对无效输入的断言失败的更多相关文章

随机推荐