Search code examples
objective-cswiftarduinonsurlnsurlrequest

Simply request an url in Swift


I have running a very basic web server on my arduino which turns the led on when typing in the url (.../?ledOn) and turning it off when typing in (.../?ledOff).

Now i have found a video on how to control these two states with a very simple looking objective c code from this website here:

- (IBAction)switchPressed:(id)sender { 
    UISwitch *theSwitch = (UISwitch *) sender; 
    if (theSwitch.isOn) { 
        NSURL *url = [NSURL URLWithString:@".../?ledOn"]; 
        NSURLRequest *req = [NSURLRequest requestWithURL:url]; 
        [myWebView loadRequest:req]
    }
}

So i tried to convert this code into swift, but there is an error, while creating the NSURL variable, I get a variable of type NSURL?


The current Swift attempt looks like:

var url = NSURL(string: ".../?buttonOn") 
var reqest = NSURLRequest(URL: NSURL(url))

Solution

  • I'd suggest replacing web view with NSURLSession call. This, by the way, eliminates the need to build the NSURLRequest, too.

    Thus:

    @IBAction func switchPressed(sender: UISwitch) {
        if sender.on {
            let url = NSURL(string: ".../?ledOn")!
            let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
                // parse `data` or examine `error` here, e.g.
                //
                // if error != nil {
                //     println("\(error)")
                // }
            }
            task.resume()
        }
    }
    

    Or, if you need to update the UI reporting the error, make sure to dispatch that back to the main queue:

    @IBAction func switchPressed(sender: UISwitch) {
        if sender.on {
            let url = NSURL(string: ".../?ledOn")!
            let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
                if error != nil {
                    dispatch_async(dispatch_get_main_queue()) {
                        //update UI reporting error here
                    }
                }
            }
            task.resume()
        }
    }