将 webhook 响应预填充到 SwiftUI 中的文本字段中

Pre-fill a webhook response into the text field in SwiftUI

我在 Swift Playgrounds 中制作了一个简单的 SwiftUI webhook 应用程序,令人惊讶的是它在发出 HTTP 请求时支持 URLSession。现在我想看看是否有一种方法可以在 POST 请求后获取该响应(例如,来自 RequestBIN),并将其预填充到一个简单的文本区域中。

这是代码

struct ContentView: View {
    @State private var TweetID = ""
    
    var body: some View {
        NavigationView {
            Form {
                Section(footer: Text("Where it should place the response data")) {
                    TextField("Field to place response data", text: $TweetID)
                }
                Section {
                    Button("Get Data") {
                        self.RequestTest()
                    }
                }
            }
        }
    }
    func RequestTest() {
        
        
        
        let semaphore = DispatchSemaphore (value: 0)
    
        let parameters = "Foo=Bar"
        let postData =  parameters.data(using: .utf8)
        

        var request = URLRequest(url: URL(string: "https://requestbin.net/r/OMG_IT_DOES")!,timeoutInterval: Double.infinity)
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        
        request.httpMethod = "POST"
        request.httpBody = postData
        
        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()
        
        
    }
}

请注意,我猜代码 print(String(data: data, encoding: .utf8)!)data 是填写文本字段所需的响应,它是......我猜 ID 或变量范围 whatmacallsit $TweetID

尝试使用此示例代码来获取请求的数据并将其显示在您的视图中:

EDIT-2:为可能的警报使用完成关闭。

struct ContentView: View {
    @State private var response = ""
    @State private var showAlert = false
    
    var body: some View {
        NavigationView {
            Form {
                Section(footer: Text(response)) {
                    TextField("Field to place response data", text: $response)
                }
                Section {
                    Button("Get Data") {
                        requestTest() { results in
                            response = results
                            if response == "No Data!" {
                                showAlert = true
                            }
                        }
                    }
                }
            }
        .alert(isPresented: $showAlert) {
            Alert(title: Text("alertTitle"), message: Text("error"), dismissButton: .default(Text("OK")))
        }
        }
    }
    
    func requestTest(completion: @escaping(String) -> ()) {   // <--- here completion closure
        if let url = URL(string: "https://requestbin.net/r/d21yhb0r") {
            
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            
            var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
            components.queryItems = [ URLQueryItem(name: "Foo", value: "BAR") ]
            
            if let query = components.url!.query {
                request.httpBody = Data(query.utf8)
            }

            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                if let data = data,
                   let apiResponse = String(data: data, encoding: .utf8) {
                    completion(apiResponse)  // <--- here
                } else {
                    completion("No Data!")   // <--- here
                }
            }
            task.resume()
        }
    }
    
}