call to URL from Swift

0

Good morning. Following the development of an app connected to a relay board through the network I have encountered a problem.

I have a board connected to a network with an ip: 192.168.0.190

to activate or deactivate the relays simply I have to call with the browser to link to activate the 1 or link to turn it off

Well, I have done it through this method and I would like you to tell me if simply to make that call (you do not have to execute or process any HTML) could be done more easily, or if this is correct at least:

func realizoConexion(cadena:String){


    let ip=UserDefaults.standard.string(forKey: "ipplaca")
    var cadenaFinal:String="http://"+ip!+cadena
      print(cadenaFinal)
    var request=NSMutableURLRequest(url:NSURL(string: cadenaFinal)! as URL)
    var session=URLSession.shared
    request.httpMethod="POST"


    var task=session.dataTask(with: NSURL(string: cadenaFinal)! as URL)


    task.resume()





}
    
asked by Sergio Cv 05.10.2016 в 17:08
source

2 answers

1

You can do it more easily using Alamofire

Alamofire.request("http://192.168.0.190/Activo1").validate().responseJSON { response in
    switch response.result {
    case .success:
        print("Validation Successful")
    case .failure(let error):
        print(error)
    }
}
    
answered by 05.10.2016 в 18:55
0

I think the focus of your code is fine but organizing it would be cleaner, something like this:

let ip = "192.168.0.190"
let endpoint = "Activo1"

let stringURL = "http://\(ip)/\(endpoint)"
let url = URL(string: stringURL)!

var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = URLSession.shared.dataTask(with: request)
task.resume()
    
answered by 07.02.2017 в 03:29