MxM
MxM

Reputation: 249

Swift - Error : Socket SO_ERROR [61: Connection refused]

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.

Upvotes: 12

Views: 23996

Answers (2)

Tangerine Coder
Tangerine Coder

Reputation: 11

Happened to me a while ago! So the developer kit has its own network so you cannot connect to localhost or 127.0.0.1 there, so get your ip:

ifconfig en0 | grep 'inet ' | awk '{print $2}'

and then do the query with it

let url = URL(string :"http://192.168.1.XXX:8080/dish)!

Upvotes: 1

user8716887
user8716887

Reputation:

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

Upvotes: 15

Related Questions