Search code examples
swifturlsession

swift - URL send data to server


So I am needing to send a simple query to the server from swift.

I thought the following would work however I am getting

Cannot convert value of type '(Data?, URLResponse?, Error?) -> ()' to expected argument type '(Data?, URLResponse?, Error?) -> Void'

Wondering if anyone knows why>?

let locationurl = URL(string: "https://api.drn1.com.au:9000/listener?uuid=\(uuid ?? "")&lat=\(location.latitude)&long=\(location.longitude)")!

    URLSession.shared.dataTask(with: locationurl) { (data: Data?, response: URLResponse?, error: Error?) in
        if let error = error {
             // Handle Error
             return
         }
         guard let response = response else {
             // Handle Empty Response
             return
         }
         guard let data = data else {
             // Handle Empty Data
             return
         }
         // Handle Decode Data into Model
    }

Solution

  •     let url = "Write here the URL"
         let request : NSMutableURLRequest = NSMutableURLRequest()
         request.url = URL(string: String(format: "%@", url))
         request.httpMethod = "POST"
    
         let task = URLSession.shared.dataTask(with: request as URLRequest) {
                (data, response, error) in
    
    
           guard error == nil else {
    
              print("error calling POST on HitServices is\(String(describing: error))")
    
              return
           }
    
           guard let responseData = data else {
              print("Error: did not receive data")
              return
           }
    
        }
        task.resume()