call to URL from Swift


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:

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
    var request=NSMutableURLRequest(url:NSURL(string: cadenaFinal)! as URL)
    var session=URLSession.shared

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


asked by Sergio Cv 05.10.2016 в 17:08

2 answers


You can do it more easily using Alamofire

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

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

let ip = ""
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)
answered by 07.02.2017 в 03:29