use swift fetch iciba API

Pub Date: 2023-09-26

 import Foundation

@main
public struct iciba_fetch {
    public private(set) var text = "start fetch.."

    public static func main() {
        print(iciba_fetch().text)
        fetch()
    }
}
//fetch
func fetch(){
    let semaphore = DispatchSemaphore (value: 0)

    var request = URLRequest(url: URL(string: "https://dict-mobile.iciba.com/interface/index.php?c=word&m=getsuggest&nums=10&is_need_mean=1&word=gap")!,timeoutInterval: Double.infinity)
    request.addValue(" Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/120.0", forHTTPHeaderField: "User-Agent")
    request.addValue("*/*", forHTTPHeaderField: "Accept")
    request.addValue("dict-mobile.iciba.com", forHTTPHeaderField: "Host")
    request.addValue("keep-alive", forHTTPHeaderField: "Connection")

    request.httpMethod = "GET"

    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data else {
        print(String(describing: error))
        semaphore.signal()
        return
    }
    print(String(data: data, encoding: .utf8)!)
    semaphore.signal()
    }

    task.resume()
    semaphore.wait()
}