swift iOS AppIntent中的HTTP请求

q3qa4bjr  于 2023-10-15  发布在  Swift
关注(0)|答案(1)|浏览(132)

我是Swift的新手,我不知道如何制作一个AppIntent,其结果是http-get请求的响应。
下面是我目前所得到的,但是由于performHTTPGet函数是异步的,我不知道如何在perform()函数中获得它的响应。

struct HttpGet: AppIntent {
    
    static var title: LocalizedStringResource = "Get API Result"
    
    func perform() async throws -> some IntentResult & ProvidesDialog {
        performHTTPGet(for: "https://my-server-api")
        return .result(dialog: "API response should be here")
    }
    
    private func performHTTPGet(for url: String) {
        guard let url = URL(string: "\(url)") else { return }

        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("Error: \(error.localizedDescription)")
                return
            }

            if let data = data {
                if let responseString = String(data: data, encoding: .utf8) {
                    print("HTTP GET Response: \(responseString)")
                }
            }
        }.resume()
    }
}
6ss1mwsb

6ss1mwsb1#

这些评论把我带到了正确的方向。下面是我如何使用javascript/await解决它:

struct HttpGet: AppIntent {
    
    static var title: LocalizedStringResource = "Get website text"
    
    @Parameter(title: "Website", description: "Website", requestValueDialog: "Enter website")
    var website: String

    
    func perform() async throws -> some IntentResult & ProvidesDialog {
        do {
            let response = try await fetchWithAsyncURLSession(for: website)
            return .result(dialog: "\(response)")
        } catch {
            return .result(dialog: "Failed to get server response.")
        }
    }
    
    private func fetchWithAsyncURLSession(for url: String) async throws -> String {
        guard let url = URL(string: url) else {
            return "Invalid URL."
        }

        let (data, _) = try await URLSession.shared.data(from: url)

        if let responseString = String(data: data, encoding: .utf8) {
            return responseString
        }
        return "Invald server response."
    }
}

相关问题