BrowserSearchService.swift
1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//
// BrowserSearchService.swift
// Pro Seecurity VPN
//
// Created by Leyter on 30.05.2023.
//
import Foundation
import Alamofire
class BrowserSearchService {
private let baseUrl = "https://suggestqueries.google.com/complete/search?output=toolbar&hl=%@&q=%@"
func searchSuggest(_ query: String) async -> [String] {
let url = String(format: baseUrl, Locale.current.languageCode ?? "", query.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? "")
guard let xmlResponse = await AF.request(url, method: .get).serializingString().response.value?.data(using: .utf8) else {
return []
}
let parser = XMLParser(data: xmlResponse)
let delegate = XMLParserSearchResponseDelegate()
parser.delegate = delegate
parser.parse()
return delegate.dataNames
}
}
// MARK: parser
extension BrowserSearchService {
class XMLParserSearchResponseDelegate: NSObject, XMLParserDelegate {
var dataNames: [String] = []
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName == "suggestion", let data = attributeDict["data"] {
dataNames.append(data)
}
}
}
}