BrowserSearchService.swift 1.34 KB
//
//  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)
            }
        }
    }
}