CHAPTER 7 ■ IOT PATTERNS: ON-DEMAND CLIENTS
At this point, your ViewController.swift should look similar to Listing 7-10.
Listing 7-10. Action Code in ViewController.swift
import U]IKit
class ViewController: UIViewController {
@IBOutlet weak var parkingSpots: UILabel!
@IBAction func refreshParkingSpotsCount(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically
// from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Now you are going to add code that needs to execute in response to a Button clicked
action. Add all the code in the refreshParkingSpotsCount(sender: AnyObject) function.
The code provided in Listing 7-11 first sends a request to the URL http://bookapps.
codifythings.com/smartparking/getcount.php. The PHP response service that you
wrote earlier sends the parking spots count in JSON format back to the client. The
next piece of code parses this JSON response and extracts the count value using the
PARKING_SPOTS_COUNT key. Finally, it updates the parkingSpots label with an updated
count of open parking spots.
Listing 7-11. Complete Code for ViewController
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var parkingSpots: UILabel!
@IBAction func refreshParkingSpotsCount(sender: AnyObject) {
let url = NSURL(string: "http://bookapps.codifythings.com/
smartparking/getcount.php")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue:
NSOperationQueue.mainQueue()) {(response, data, error) in