Networking in Swift: Building the Swift Client, Part 2

In the first part of this tutorial segment on networking in Swift, we got our client app up and running with a simple table view controller listing the two inventories supplied by the RESTful API we created in the initial segment of the series. In the present article, we will: 1) set up our data model, 2) create the segues to our inventory views, and 3) process raw responses from the server asynchronously. 

Building the Item Data Model
Our code looks better and becomes easier to manage when we build objects that represent or model the data items that we receive from our web service. To this end, we'll create a file for our individual plumbing supply items using a Cocoa Touch Class template, and then fill it out with the necessary parameters supplied by the API. Open up your Xcode project if you haven't already. In the Xcode Project Navigator panel, right click on the top most group folder. From the menu options that appear, select new file.



You will be presented with a set of options similar to this:


Under iOS, select Source, followed by Cocoa Touch Class, then click Next. Under the secondary menu options: next to the 'Class' field type in PlumbingSupplyItem. For the next field, 'Subclass of', type NSObject, do not create a XIB file (uncheck box), and for the Language portion ensure that Swift is selected:


Click 'Next'. When prompted to select a destination, place the file alongside the other project files. If the file is not automatically loaded into Xcode, then open it from the Project Navigator panel. Now place the following code within the PlumbingSupplyItem class implementation:

As you can see, this code block models the data item passed from the RESTful API we built in the previous segment of this tutorial series, initializing an item id, an item name, an associated image and an item description. It doesn't get much simpler than this.

Segues to the Inventory
With our data model in place, we'll now create our controller class for our inventory, using a table view. This will allow us to mediate between the two inventory table views upon a touch event by the end user.

In the same manner that we created the PlumbingSupplyItem model file, create a new file named PlumbingSupplyInventoryTableViewController using a Cocoa Touch template, and have this file subclass a UITableViewController. From the Object Library, located in the Utilities panel, drag and drop two UITableViewControllers into the main storyboard as depicted below:

Select one of the two view controllers that were just dropped in. Now, in the Identity Inspector, located in the Utilities panel, find the Class field, and type in the name of the class we just created (i.e. PlumbingSupplyInventoryTableViewController) as shown below:

Do the same for the other controller as well, since we are building two separate views of the same kind of object, i.e. items in each of our two inventories.

Note that when you are zoomed out in a storyboard, you can only make selections on the view controllers themselves. To make selections on a controller's internal elements, you have to zoom in. Armed with that information, go ahead and select the cell with the label 'Plumbing Tools'. While holding down the Control key and the left mouse button, drag your mouse over to the top right most view controller and release. During this motion you should see a blue line stretch from our starting location, the table view cell, to our final destination, the view controller.


Upon releasing your mouse button over the controller, a menu will appear. Select the top option that reads: Selection Segue->Show.


Now repeat the same steps for the other cell as well. Your storyboard should look like the following:

What did we just accomplished? We have set up view controller view transition objects known as segues. These segues will respond to a user's touch of a cell. When a cell is pressed, the associated segue will transition to the view controller that it points to.

Preparing Our Segue
Since we will be using a single view controller to display the different inventories of plumbing supplies from the two possible options, namely, Plumbing Tools and Copper Pipes and Fittings, we need to inform the destination view controller which cell was selected. The tip of a segue arrow is said to point to the destination view controller and the tail of the arrow is said to originate from the source view controller. Create a file named PlumbingSupplyCategoriesTableViewController and have this file subclass a UITableViewController.

Now we'll hook it up on the story board. Select the source view controller, i.e. the controller with the two cells. In the Identity Inspector, located in the Utilities panel, where the field reads 'Class', type in the name of the file and class we just created: PlumbingSupplyCategoriesTableViewController. In the main storyboard, select the segue arrow that is associated with the cell labeled 'Plumbing Tools'. From the Attributes Inspector, located under the Utilities panel, locate the Identifier field and type in: plumbingTools.

Do the same for the other segue arrow, but this time provide the Identifier with the name from the title of the other inventory list: copperPipesAndFittings.

We're now going to jump back to our code files. In the PlumbingSupplyInventoryTableViewController.swift file, place the following code (in line 3 below) immediately after the class definition, like so:

Now, over in the PlumbingSupplyCategoriesTableViewController.swift file, replace all the code inside the class PlumbingSupplyCategoriesTableViewController: UITableViewController { . . . } with the following snippet:


This is a system call method that is responsible for notifying the source view controller that a segue is about to be performed. The title that we set in the code above is to the destination table view controller that we segue to. On this destination controller we also set the plumbing inventory url endpoint so that the controller can load the content that was chosen by its corresponding table view cell. Our destination has enough information to load the entire inventory of the selected plumbing category.

Holding Pattern: Activity Indicator
Before we request a list of inventory items, it is customary to run an activity indicator to show the user that our app is in the process of getting some information to display. In the PlumbingSupplyInventoryTableViewController.swift file, below the line of code that reads var inventoryUrlEndpoint : String = "", enter the following line of code:

This line of code creates an instance of UIActivityIndicatorView and makes it private. Now we're going to fill it out inside the viewDidLoad method. In the same file, but inside the method override func viewDidLoad(), add the following lines:


Save all your files and run the application. Once it loads, segue to the two inventory table view controllers. You should see an activity indicator animation as shown here:

Requesting an Inventory
Inside the PlumbingSupplyInventoryTableViewController.swift file, immediately below the webActivityIndicator property, we'll now define another variable that holds a reference to a URL session object that will asynchronously handle our web request. Enter the following line there:
var urlSession = NSURLSession.sharedSession()
At the bottom of the same class, we now define a function that will perform the url session request, parse the request and send us back objects if the success was successful. Here's our first stab:

If you are new to Swift, this function might look rather cryptic. That's because it is! It was no easy task to get this right—a whole lot of Google engineering was required on our end. Lets break it down by parameter:

    'endPointURL : String'
        - 'endPointURL' is an arbitrarily chosen parameter name that we defined in order to identify this parameter, and the 'String' portion requires that the passed in object be of string type.

    'responseHandler'
        - 'responseHandler' is an arbitrarily chosen name for our closure, a.k.a block in Objective-C.

    'error : NSError?, items : Array<PlumbingSuppleyItem>?) → ()'
        - This portion defines a closure.
        - The 'error : NSError?' segment is again an arbitrarily chosen parameter name, and the 'NSError' portion requires that the passed in item be of NSError type.
        - The question mark (?) indicates that the passed in object is optional, meaning that a nil may be provided—in its absence we are required to pass in a none nil value NSError object.
        - 'items : Array<PlumbingSupplyItems>' indicates that the passed in object is a container that holds objects of PlumbingSupplyItem type. 
        - The arrow followed by the parenthesis '→ ()' indicates that this closure returns no values. Instead, objects are passed through the closure's callback parameters.
        - The second arrow followed by parenthesis '→ ()' indicates that the function returns no values.
        - The arrow along with the parenthesis may be omitted for both the function and closure.

Okay, that was a mouthful, but what happens when the view appears on the screen? Let's define it. Right below the viewDidLoad method, we add the following code for our new viewDidAppear method:

This function will be called by the system when the view appears onto the screen. This is good spot to begin requesting inventory items. Notice that we are calling our previously defined requestInventory function. Let's revisit that function now. Replace all the existing code inside the requestInventory method implementation, with the following snippet:


Let's go through this line by line. Line 1 creates an NSURL object from the provided endPointURL string that is referenced by a constant named url; it is essentially a wrapper object for a string formatted URL. This NSURL object is required by our urlSession object that is on the next line of code.

On this line of code, i.e. line 2, we create what is known as a 'data task' for querying our web service. This call spawns an asynchronous operation that communicates with our PHP web service without blocking the main thread. Not blocking the main thread is highly desired if we want our user interface to continue to be responsive—this makes for a better end user experience. Once the communication with our web service completes, the completionHandler closure and all of our code that is contained within this closure is executed. The closure has three parameters: 1) the raw data that comes from our web service, 2) a response object containing the headers from our web service response, or 3) an error object if the request failed.

Line 4 prints the response object inside the Xcode console.

Line 6 is a call to a closure that we defined for our requestInventory function. The parameters provided are an error object if any, and a list of data objects for our inventory items. Currently, we only return nil values. 

Run the application the select both Plumbing Tools and Copper Pipes and Fittings table view cells. You should see the response objects printed for both selections in your Xcode console. The responses in your Xcode console should look similar to this:


Success! Notice that the response object is of type NSHTTPURLResponse. This response object contains information about the requesting url, and the header fields from our web services. Notice the status code of 200; this means that request was completed without issue. You can also print the data object but in its raw form it will not make much sense—try it if you'd like. The communiqué between the host and client is comprised of two parts. The first part is known as the head or header and the second part is known as the body. A typical request or response will contain both of these parts (It's possible to just request the head of a web service response—Google to find out how). The real-world analogy that is often used to describe this is paper mail. The electricity bill, for example, is comprised of two parts as well. The first part is the envelope itself that contains information about its sender—the head. The second part is the contents of the envelope that contains information for the recipient—the body.

JSON Parsing
Now let's get our raw inventory. To do this, we take the response or body of the message and translate it into a container that we can readily read from. In the same function that we've been working on, replace the following line of code that prints out the response, (i.e. println(response), line 4 in the snippet above) with the following:

The first line of code creates a parse error pointer to an object of type NSError, or nil value. On line 2, we call the NSJSONSerialization class method JSONObjectWithData(. . .) and pass to it our raw data response from our web service along with the memory address of the pointer that we created on the first line.

This last method will convert our raw data into a mutable container of type NSDictionary. If the conversion process fails, then this method will assign an error object to the provided memory address with a description or nature of the failure.

The last line of code simply prints our newly created container to the console screen. Save the file then build and run the application. Navigate to one of the inventory endpoints from the table view. In the Xcode console, you should see a similar response to this:


This project can be found on GitHub.

Success! Our application is now querying our tools and supplies API, and returning the inventory response for each of the categories listed on our primary view controller. In the next article in the series, we'll create model objects and then display our inventory item list in our Swift client. Continue to part three on building the Swift client.

Index
Introduction
Introduction and Overview: From the Back End API to the End User Application

The Web API
Building a RESTful API in PHP, Part 1
Building a RESTful API in PHP, Part 2

The Swift Client App
Networking in Swift: Building the Swift Client, Part 1
Networking in Swift: Building the Swift Client, Part 2
Networking in Swift: Building the Swift Client, Part 3
Networking in Swift: Building the Swift Client, Part 4
Networking in Swift: Building the Swift Client, Part 5


This tutorial was authored by Stefan Agapie, a Senior iOS Software Engineer, and adapted for the present piece. 

Become An Instant Connoisseur With "Vivino" Wine App

Want to imbibe wine like you're fancy, but have no idea where to begin?  No worries, with the new Vivino app, you'll be able to find the greatest of the grapes, using only your smartphone.

Simply upload a photo of any wine label that strikes your fancy, and you'll be able to immediately access pertinent information, reviews, ratings, and price guides.  With over 6 million users contributing feedback using a 1 to 5 star ratings scale, you can get a good feel for what's smooth sipping versus swill.

While the old-fashioned way of just trying everything also works, with Vivino there's a way to help you accurately REMEMBER your favorites.
(Image courtesy wikimedia.org.)

As reported by winderlusting.com, Vivino can also sync with your social media.  Linking with Facebook, Twitter, Google, and more, you can interact with other oenophiles who may share your same tastes.  This also enables the casual drinker to follow more seasoned sommeliers who can offer a wide variety of personal experience.

The Vivino app is free and works on all iPhone, Android, and Windows smartphones.  A $4.99 upgrade is also available for those who want to track sizeable selections for their cellar.  So whether you're a collector or just wondering about what you're housing down at happy hour, Vivino can help you perfect your palate.

Seriously, you can do better than this.
(Image courtesy iwishilikedflan.com.)

Networking in Swift: Building the Swift Client, Part 1

If you've been following along from the beginning of this tutorial series on networking in Swift, you're now running a local web server and have created a simple RESTful API in PHP that serves up the inventory for our hypothetical Super PHPlumbing Bros. project. In this segment of the series, we'll build the iOS Swift client to bring that content to our end user. In the present article, we'll start our Swift project from scratch and create a single view application using a table view controller that will serve as the primary interface to our inventory of plumbing tools and supplies.

In the Beginning . . . 
Download and install the latest version of Xcode, if you haven't already, and fire it up. From the Xcode menu bar (or the Welcome screen) select File->New->Project. A window will appear with various options to choose from. In the left hand panel, under iOS, choose 'Application'. And in the main panel select 'Single View Application'. Then go ahead and click 'Next' as shown below.

On the following window you will be asked to name your application. Name it what ever you like. Under the Language section select Swift from the drop down menu. Make sure that the build is for iPhone in the 'Devices' menu, and then click 'Next' again.

You'll then be prompted to choose a location to house your project and will be given the option to place the project under source control. If you know how to use git for source control, then by all means use it! Otherwise, uncheck the box if it is already checked and click 'Create' to start up the project.

Displaying the Available Services
In our Swift application, we want to present the user with all the available services that our supply shop has to offer. Our custom API provides an interface to our inventory of Plumbing Tools as well as our inventory of Copper Pipes and Fittings. To present these options to the end user we are going to use a table view. So let's jump in. In the navigator panel (the left panel) of Xcode, locate and select the file named Main.storyboard.

Once the main storyboard loads, scroll to the pre-loaded Single View Controller and select it. When properly selected its border will turn blue, as seen here:

As we are going to use a table view, we can safely discard this default view controller. Delete the single View Controller by pressing the delete key on your keyboard, while the controller is selected. In the Utilities Panel on the right side of the Xcode interface, locate the Object Library submenu. Select a Table View Controller, and drag and drop it inside the main storyboard. 

While the new controller is selected, point your mouse toward Xcode's menu bar and select: Editor->Embed In->Navigation Controller. This embeds our selected Table View Controller into, you guessed it, a Navigation Controller.



A Navigation Controller is a stack for managing the presentation order of our view controllers. Select the Table View situated inside the Table View Controller, and then select the Attributes Inspector from the Utilities Panel. Locate the 'Content' field and select 'Static Cells' from its drop down menu.


You should see three cells appear inside the Table View. We only need two such cells, as this is where the user will be presented with the option to browse either the Plumbing Tools inventory or the Copper Pipes and Fittings inventory. Delete the bottom cell by first selecting it, and then pressing the delete key on your keyboard. Now let's name our two primary interfaces. For each of the two remaining cells, select the cell, and then locate the 'Style' field in the Attributes Inspector panel. From the 'Style' drop down menu select 'Basic'.


Both table view cells should now display a label that reads 'Title'. Two clicks in rapid succession on a label will place it into edit mode. Modify the titles so that they read from top to bottom, 'Plumbing Tools' and 'Copper Pipes and Fittings', respectively.

In order for the application to run, we need to specify the initial view controller that we want to load when the application first boots up. In the main storyboard, select the Navigation Controller. Then, in the Attributes Inspector menu, locate the check box that reads, 'Is Initial View Controller' and select it as shown below:

In the top left corner of Xcode make sure that the active scheme is set, and click the play button to build and run the application. Once the iOS simulator starts up, your app should look like this:

This project can be found on GitHub.

Success! We've built the primary view that will be presented to the end user when they open our iOS application. In part two of this segment, we'll begin building our data models. You can find part two in the tutorial on building the Swift client at the link.

Index
Introduction
Introduction and Overview: From the Back End API to the End User Application

The Web API
Building a RESTful API in PHP, Part 1
Building a RESTful API in PHP, Part 2

The Swift Client App
Networking in Swift: Building the Swift Client, Part 1
Networking in Swift: Building the Swift Client, Part 2
Networking in Swift: Building the Swift Client, Part 3
Networking in Swift: Building the Swift Client, Part 4
Networking in Swift: Building the Swift Client, Part 5

This tutorial was authored by Stefan Agapie, a Senior iOS Software Engineer, and adapted for the present piece. 

Foils, Not Oil: Emission-Free "Quadrofoil" Boat To Debut In 2015

If you're already over the wintry weather and just want summer to get here again, here is some post-Halloween brain candy for you.  Check out what techplus24.com calls the "21st century's answer to the speedboat":  the Quadrofoil.

Chicks dig ecologically-conscious mariners.
(Image courtesy gizmag.com.)

Using C-shaped foils beneath the hull to create lift, the Quadrofoil appears to hover above the water.   The foils deflect the water downward, creating lift and exerting force that enables the craft to travel at 25 m.p.h.  The Quadrofoil can transport two passengers and is made of 220 pounds of lightweight composite materials.  It is nearly theft-proof, thanks to a detachable wheel that acts as its key.

Best of all, the Quadrofoil operates on an electric motor, which creates no unpleasant emissions and makes considerably less noise than conventional motorboats.  The cleanliness of the craft allows it to operate on lakes, rivers, and ecologically-protected areas that might not be happy to harbor other messier boats.  Seeking out these spots is easy, with a single charge of the battery enabling the Quadrofoil to travel for 62 miles (at a cost of about $1.30 an hour to run.)  Don't just watch the meniscus-meandering water bugs from the dock...now, you can act like one too!

Make jetskiiers jealous.
(Image courtesy diseno-art.com.)


The Quadrofoil ships in March of 2015 at a cost of $28,144.  Next summer may seem like a long time away, but this little floating fragment of future is something fun to look forward to.

We can't all have spaceships.  But lakeships?  There you go.
(Image courtesy theawesomer.com.)

Score Scorchy Selfies With New Thermal-Imaging Smartphone Camera

What new photo tool brings the real hotness for your smartphone?  Literally?  How about your own personal thermal imaging camera?

According to redferret.net, the Seek Thermal Imaging Camera is a new iPhone and Android-operable device that turns your smartphone into something like you'd spot in a cool spy movie.  Thermal imaging cameras, which use infrared technology to sense the presence of heat, make any temperature-producing item visible, regardless of lighting conditions.  Ninjas hiding in your house at night?  Not anymore, you spotted them with Seek!

Your evil black cat may resent his fresh lack of hiding skills.
(Image courtesy NASA.gov.)

The Seek can detect heat signatures at up to 1,000 feet, recognize more resolutely at 250 feet, and identify specifics at 150 feet.  As their product description explains, "Our eyes rely on light to see, Seek Thermal relies on heat."  It has a spectrum from -40 degrees to 330 degrees Celsius, so you can just as easily determine if your drink is acceptably ice-cold as you can gauge how well-done your burgers are.

Your pet penguins can be kept suitably chill thanks to infrared analysis.
(Image courtesy boingboing.net.)

For $199, the 8-ounce, micro-USB-enabled Seek can capture all the hotness (or coolness) around you.  It's the same technology that NASA uses to spot space phenomena, surely you too can come up with some interesting experiments!  Besides, wasn't that sepia filter starting to get boring anyway?


AAHHHH, FLAMETHROWER ATTACK!  Oh no, just a hairdryer in infrared.
(Image courtesy NASA.gov.)




Does Mario Dream Of Electric Sheep? Nintendo To Create Sleep-Monitoring Device

Do you wake up sometimes wondering if you're just unhappy to be headed to work, or if you're actually experiencing sleep deprivation?  Do you wonder about how your sleep cycles are affected by various activities you may be hitting up before you hit the sack?  Soon, a device made by (stop laughing) Nintendo will be able to help you determine how healthy your sleep patterns are.

According to techlandra.com, Nintendo's president, Satoru Iwata, isn't just talking about a novelty invention.  This is a whole new means of categorizing a previously-unquantified issue that affects every human on earth.  "Since fatigue per se is not regarded as a disease in the medical world, it is said to be a field where sufficient research has yet to be conducted," Iwata said. "We have been fortunate to encounter several experts who have been conducting cutting-edge research in the science of fatigue. Together, we are now developing technology to estimate fatigue."

Optional dream-controlling hopefully to follow.
(Image courtesy uberreview.com.)

The device, as reported by Reuters, is as of yet unnamed but is planned to debut in 2015.  Developed in conjunction with the medical device company ResMed, the sleep-assessment system will be small enough to easily sit on your nightstand.  Using microwave sensors that do not come into contact with the body, the quality and length of sleep cycles are tracked and then sent to attendant apps for analysis.

This creation is part of Nintendo's new "Quality Of Life" initiative, which according to gamesindustry.biz seeks to "improve peoples' quality of life in enjoyable ways."  The new sleeping device will abide by five simple principles:  it need not be worn by the user, it need not touch the user at all, it need not be booted up by the user to begin working (it assesses things like body movement, heartbeat and breathing autonomously to determine sleep cycles), it provides data immediately, and it requires no complicated setup.

In other words, it's as easy as falling asleep!  And if you can't even do that right, Nintendo's new machine can help you.

If you get a good night's sleep, maybe you can work your way up to Player 1 status.
(Image courtesy builttoplay.ca.)

Shine On, Mine On: Solar And Wind Power Make Electricity 70% Cheaper For Mining


The clean energy revolution could stand to gain many supporters when it's proven to work effectively for big business.  Now, the mining industry is looking towards alternative energy to fuel their pursuits, with some interesting and prosperous results.

As reported by cleantechnica.com, renewable solar and wind power is up to 70% more cost-effective for the mining industry than diesel fuel - a startling revelation.  With many remote mining areas amenable to wind and unhindered sunlight,  as well as factoring in the cost of NOT having to truck fuel out to the far-flung sites, the benefits of going green begin to add up considerably.

Dig this:  it's a bright future thanks to solar power (and other renewables.)
(Image courtesy energymanagertoday.com.)

One Australian mining site uses solar power to the tune of offsetting some 600,000 gallons of diesel fuel.  Another Alabama steel mill is run mainly on solar power, and one of the world's preeminent copper mining companies is set to follow suit with a 70 MW solar array.  It's not just for hippies anymore.  If the metal crews are into it, what's to stop the rest of society?

For those who would be interested in arming their business with the might of the sun, there exists an online aggregator of clean tech called Renewables And Mining.  It contains information on "Photovoltaics, concentrated photovoltaics, concentrated solar power, solar thermal, and wind power" for comparison to assess what might work best for a particular type of industrial site.  Why spend tons when you can invest in the sun?  For those who work at removing some of the precious things the environment has to offer, why not harness a similar energy for the harvesting itself?

Even old mines can get in on the usefulness!
(Image courtesy spiegel.de.)