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

I made a simple SwiftUI webhook app in Swift Playgrounds that surprisingly supports URLSession when making a HTTP request. Now what I would like to see if there is a way to take that response (for instance, from RequestBIN) after a POST request, and prefill it into a simple text area.

Here’s the code

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://YIKES")!,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()
        
        
    }
}

note that I guess the code print(String(data: data, encoding: .utf8)!) that whereas data is the response needed to fill in the text field which is......I guess the ID or varible scope whatmacallsit $TweetID

If you’re using the latest stuff (Swift Playgrounds 4.0 on iPadOS 15) then you can use its shiny new async/await support for this. WWDC 2021 Session 10019 Discover concurrency in SwiftUI has some great examples of this.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

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