I want to connect a web server to my ios application with swift. So I created a function to create a task with "POST" but when I call it, I get an error message :
nw_socket_handle_socket_event [C1.1:2] Socket SO_ERROR [61: Connection refused]
My code :
func createDish(dish :Dish) {
let url = URL(string :"http://localhost:8080/dish)!
var request = URLRequest(url :url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
if let data = try? JSONEncoder().encode(dish) {
request.httpBody = data
}
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print(error.localizedDescription)
return
}
if let data = data {
if let dish = try? JSONDecoder().decode(Dish.self, from: data)
{
self.dishes.append(dish)
}
}
}.resume()
}
I don't know at all where the error comes from, if it's in my app or server code. Thank you for your response.
I had a similar problem.
After replacing the localhost with a machine's IP address(ex, 192.168.100.XXX), it worked well.
How to find my ip on a mac:
https://osxdaily.com/2010/11/21/find-ip-address-mac/?fbclid=IwAR1oiq4xyvAWj9XOaG3VzGdr6TIyIbFE08PzCZLNbEu2RaQf4LUWCkFGQgY