Swift - Error : Socket SO_ERROR [61: Connection refused]
Asked Answered
B

2

11

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.

Becky answered 28/6, 2020 at 20:4 Comment(2)
Are you trying to connect to local host indeed? Can you access this url in browser from the same device? Did you try https instead?Tubman
This would be an issue with connecting to your MySQL database. Make sure that MySQL is running and that your connection configuration for your Vapor server matches what you have for your MySQL database.Gwin
K
15

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

Kincaid answered 12/7, 2020 at 14:38 Comment(2)
For finding my local IP address, I just add this alias to my .zshrc file alias myip='ifconfig en0 | grep inet | grep -v inet6 | cut -d" " -f2'. I restart my shell, then type myip.Kist
Or you could try 127.0.0.1 which worked for me.Sotted
I
1

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)!
Inception answered 24/8, 2024 at 10:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.