So I have some Swift code that send a request to my local host
//
// ContentView.swift
// Shared
//
// Created by Ulto4 on 10/23/21.
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
Text("Hello, world!")
.padding()
Button(action : {
self.fu()
}, label: {
Image(systemName: "pencil").resizable().aspectRatio(contentMode:.fit)
})
}
}
func fu(){
let url = URL(string: "http://127.0.0.1:5000/232")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("Response HTTP Status code: \(response.statusCode)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
However, on my Flask app there are no get requests coming in and the function isn't running. There also isn't anything printing to the console. I am fairly new to swift so I don't really know how to fix this. Is there any other way to send requests in swift, if not, How would I fix this?
CodePudding user response:
You are creating the URLSessionDataTask
, but you never start it. Call task.resume()
.
Longer term, you might consider using Combine, e.g., dataTaskPublisher
. Combine fits well into SwiftUI patterns.
CodePudding user response:
If you are using swift 5.5, you could try the following approach. Note the https (see also: Transport security has blocked a cleartext HTTP ).
import SwiftUI
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
Text("testing")
.task {
let theData: Data? = await getData()
print("---> theData: \(theData)")
}
}
// send a request to your local host
func getData() async -> Data? {
// note the https not http, and use ! only for testing
let url = URL(string: "https://127.0.0.1:5000/232")!
do {
let (data, response) = try await URLSession.shared.data(for: URLRequest(url: url))
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print(URLError(.badServerResponse))
return nil
}
return data
}
catch {
return nil
}
}
}