cloud-dns-ios/dns/BlockedCount.swift

77 lines
1.9 KiB
Swift
Raw Normal View History

2026-04-13 14:18:42 +01:00
import SwiftUI
import Foundation
struct BlockedCount: View {
2026-04-13 14:18:42 +01:00
@State private var txtRecord: String = "..."
private static let startIndex = 44
private static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
2026-04-13 14:18:42 +01:00
var body: some View {
Text(txtRecord)
.onAppear {
fetchTXTRecord()
}
}
func parseResponse(data: Data) -> String? {
// This is a DNS wire format response and we make a lot of assumptions
// It is not critical functionality so just let it fail if it fails
guard data.count > Self.startIndex else {
return nil
2026-04-13 14:18:42 +01:00
}
// Find the first space character (ASCII 32).
guard let endIndex = data.suffix(from: Self.startIndex).firstIndex(of: 32) else {
return nil
}
2026-04-13 14:18:42 +01:00
guard let numberString = String(data: data[Self.startIndex ..< endIndex], encoding: .utf8)
else {
return nil
}
2026-04-13 14:18:42 +01:00
return Self.formatter.string(for: Int(numberString))
2026-04-13 14:18:42 +01:00
}
func fetchTXTRecord() {
let dohURL = URL(string: "https://dns.sr2.uk/dns-query?dns=DoQBAAABAAAAAAAABXN0YXRzB2ludmFsaWQAABAAAQ")!
let request = URLRequest(url: dohURL)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async {
if error != nil {
txtRecord = "Error"
return
}
guard let data = data else {
txtRecord = "Error"
return
}
guard let count = parseResponse(data: data) else {
txtRecord = "Error"
return
}
txtRecord = count
}
}.resume()
}
}
#Preview {
BlockedCount()
}