Trick Or Treat Or Treetr? New App Handles Your Halloween

Can a classic holiday tradition be improved with a little bit of futurism?  That may be the case tonight when a new candy-canvassing app, Treetr, gives you a battle plan to NOT hit the streets.  That's right, all the fun and freakiness of Halloween night ramblings can now be outsourced, via an app.

It's like having your own personal candy concierge.
(Image courtesy twitter.com.)


As parodied by vice.com, the Treetr app (available for iPhone and Android) is "Halloween, simplified."  A network of costumed Treetr delivery men will tour the town in your place, gathering goodies and delivering them back to you for a fee.

According to Treetr's Twitter (@TreetrApp),  over 10,000 delivery-ghouls nationwide will suit up to snag you sweets.  No word on whether they'll make sure there's no razor blades or poison in the stash, and no, you cannot tip them by pawning off all your unwanted Whoppers and Raisinets.

So if you want to stay extremely, boringly, lazily safe this Halloween, hire out the haunting via Tweetr.  For every other spooky celebrant on the streets, best of luck and enjoy your sugary stroll!

Just remember what happens to people who get too greedy for candy, Treetr users!
(Image courtesy pinterest.com.)

Virgin Galactic's SpaceShipTwo Has Crashed

The scariest news this Halloween involves the continued delay of a first-rate independent space program.  Virgin Galactic's premiere tourist spacecraft, SpaceShipTwo, crashed today in the Mojave desert during a test flight.

According to the LA Times, the WhiteKnightTwo airplane, which carries the spacecraft, landed safely after a "serious anomaly" caused the crash.  One pilot is dead, while another successfully parachuted from the flight.

The SpaceShipTwo was thought to be an attractive option for space tourism, with Virgin Galactic founder Richard Branson enthusiastic about being "on the verge" of initiating commercial space travel.  Tickets for $250,000 were to ferry passengers to the edge of space, riding 50,000 feet up via the WhiteKnight plane before disengaging with SpaceShipTwo.   The spaceship would then travel at 2,500 miles per hour, toting a pilot and six passengers to the upper atmosphere, around 60 miles up.

SpaceShipTwo and WhiteKnightTwo, in better times.
(Image courtest spaceshiptourist.com.)

One possibility for the anomaly, according to NBC News, is that Virgin Galactic has switched the fuel for the aircraft in the nine months since their last test flight.  SpaceShipTwo's rubber-based fuel compound was traded for a plastic-based fuel that was thought to be able to improve the hybrid engine's function.

Earthlings, have a safe Halloween, and don't be too haunted by the failures that must occur on the path of progress.

Ad Astra Per Aspera.
(Image courtesy 10news.com.)



Networking in Swift: Building a RESTful API in PHP, Part 2

This is the third post in our tutorial series on networking in Swift. In the introductory article, we provided an overview of the project and set up our local server. In the next piece, we began building out our RESTful API in PHP, which will serve the inventory for our hypothetical Super PHPlumbing Bros. supply company to the custom Swift client we will construct in the final segment of the series.

If you've been following along thus far, you've set up your local server and completed building the first half of the API, which serves the inventory for the shop's supplies. In this article, we will complete our API by adding the necessary code to serve the content of our plumbing tools inventory.

Building the Plumbing Tools Interface
In creating the API for our plumbing tools interface, we will follow pretty much the same series of steps we took while building the plumbing supplies interface, continuing to add the necessary code to the bare bones API we started with in part one. Our skeletal structure now has some real meat on it. Your PlumbingAPI.php file should now look like this:

Jumping In . . .
Once again, let's begin toward the bottom, in the final else if block in the script, the plumbing tools API call, which begins at line 263 above. Replace the echo command in line 264 with the following code block, which contains the relevant response logic:
// build payload //
$response['code'] = 1;
$response['api_version'] = '1.0.0';
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
   
// if an 'item_id' was provided then return details for that item //
if ( $_GET['item_id'] ) {
    $response['item_id'] = strtoupper($_GET['item_id']);
    $response['data'] = plumbing_tool_item_details(strtoupper($_GET['item_id']));
}
// else return our entire inventory of plumbing tools //
else {
    $response['data'] = plumbing_tools_inventory_without_description();
}
Save your PlumbingAPI.php file and point your browser to this url, http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&format=json. The response will appear as follows in your web browser:
Plumbing Tools Inventory without Descriptions.
Plumbing Tools Inventory.
{ "code": 1, "status": 200, "data": null, "api_version": "1.0.0" }
Now let's add in our plumbing tools inventory. The relevant function begins at line 132 above (function plumbing_tools_inventory()). Replace the echo command with the following associative array:

As in part one, this array constitutes the actual content of the relevant inventory, including item ids, names, image locations, and descriptions. Let's now write the necessary code to serve up our tools inventory without the lengthy descriptions. Appropriately, this will be placed in the plumbing_tools_inventory_without_description() function, located at line 140 in the full script file above. Replace the two lines of placeholder code in that function (lines 141 and 142) with the following snippet:

// pull our entire inventory of plumbing tools //
$inventory = plumbing_tools_inventory();
   
// container for plumbing tools inventory with omitted description //
$inventory_without_details = array();
   
// iterate over the array, duplicate the inventory without descriptions//
foreach ($inventory as $key=>$value) {
    if (is_array($value)) {
        $inventory_item = array();
        foreach ($value as $subkey=>$subvalue) {
            if ( strcasecmp($subkey,'description') != 0 )
                $inventory_item[$subkey] = $subvalue;
        }
        $inventory_without_details[$key] = $inventory_item;
    }
}
return $inventory_without_details;
Save your file and point your browser to this endpoint: http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&format=json. You should see a json response for our entire inventory of plumbing tools.

Now we'll work on serving individual plumbing tools along with their descriptions. Find the plumbing_tools_item_details($item_id) function at line 176 in the script above, and replace the place-holder code in lines 177 and 178 with the following block:
// pull our entire inventory of plumbing tools //
$inventory = plumbing_tools_inventory();
   
// container for item matching the provided item_id //
$inventory_item = array();
   
// iterate through our inventory and find the requested item //
foreach ($inventory as $key=>$value) {
    if (is_array($value) && strcasecmp($value['id'], $item_id) == 0) {
        foreach ($value as $subkey=>$subvalue) {
                $inventory_item[$subkey] = $subvalue;
        }
        break;
    }
}
return $inventory_item;
Save your php file and point your browser to this url:http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&item_id=PT12010&format=json. This is an endpoint to the first item from our json inventory response for plumbing tools. You should see the following response in your browser:
{
    "code": 1,
    "status": 200,
    "data": {
        "id": "PT12010",
        "name": "Plunger.",
        "image": "http://localhost:8888/assets/plunger.png",
        "description": "Super-pliable industrial-rubber cup with tiered ridges forms ultra-tight seal on any size drain. The heavy-duty steel handle allows for maximum pressure forced down drain to source of clog. Designed to work effectively at any angle for hard-to-reach, low-clearance applications."
    },
    "api_version": "1.0.0",
    "item_id": "PT12010"
}
Our API is almost complete! Besides json, you will typically encounter web APIs that support multiple formats. Let's have our API also support XML and HTML responses. Find the deliver_response($format, $api_response) function at line 23 in the API script above, and locate the "XML Response" else if block that begins at line 49. Currently, it only has a place holder comment indicating that this is where we will our XML response logic will live. Add the following code to that block:
// Set HTTP Response Content Type //
header('Content-Type: application/xml; charset=utf-8');
       
// initializing or creating array //
$data = $api_response['data'];

// Format data into an XML response //
$xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
arrayToXml($data, $xml);
       
// Deliver formatted data //
echo $xml;
This is the next line. Notice that the HTML response logic is in the final else block of the same function. Replace the place-holder "// HTML Response //" comment with the following snippet:
// Set HTTP Response Content Type //
header('Content-Type: text/html; charset=utf-8');

// initializing ro creating array //
$data = $api_response['data'];
       
$payload = '';
$html = '';
if (is_array($data)) {
    arrayToHTML($data, $html);
    $payload = $html;
}
else {
    $payload = $data;
}
       
// Deliver formatted data //
echo $payload;
Finally, we have to fill out the arrayToXml($data, $xml) and arrayToHTML($data, $html) functions referenced in these two snippets. Find the empty arrayToXml function at line 214 in the PHP script above, and add the following to its body:
// wrap XML with $wrap TAG //
if ($wrap != null) {
    $xml .= "<$wrap>\n";
}
// main loop //
foreach ($array as $key=>$value) {
  
    if(is_array($value)) {
        // recursive call //
        arrayToXml($value, $xml,'ITEM');
    } else {
        // set tags in uppercase if needed //
        if ($upper == true) {
              $key = strtoupper($key);
            }
            // append to XML string //
            $xml .= "<$key>" . htmlspecialchars(trim($value)) . "</$key>";
    }
}
// close tag if needed //
if ($wrap != null) {
    $xml .= "</$wrap>\n";
}
Now locate the arrayToHTML function, located at line 224 in our PHP script above. Like its XML counterpart, it is currently empty. Add the following code to the body of the function:
// wrap html with $tag //
if ($tag != null) {
    $html .= "<HTML>\n";
}
// main loop //
foreach ($array as $key=>$value) {
   
    if(is_array($value)) {
        // recursive call //
        arrayToHTML($value, $html,'h1');
    } else {
        // set tags in uppercase if needed //
        if ($upper == true) {
            $key = strtoupper($key);
        }
        // append to XML string //
        $html .= "<$key>" . strtoupper($key) . ' : ' . htmlspecialchars(trim($value)) . "</$key><br>";
    }
}
// close tag if needed //
if ($tag != null) {
    $html .= "</HTML>\n";
}
Save your file and point your browser to this endpoint: http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&item_id=PT12010&format=json . You should see a json response for our entire inventory of plumbing tools. If you type in xml instead of json, in the url, you should see an xml response. Also, typing in html will result in an html response. 

Rejoice! We have completed what is arguably the hardest part of this tutorial!

Clean URLs
Although our URLs up to now were well-formed for the task, you will at times be restricted to use what is known as clean URLs to query a web service. Clean URLs are structured in such a way that the query portion of the URLs that we have been using thus far are instead inserted within the URL path. Simply put, instead of using this url, http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&format=json, to access our inventory of plumbing, we will setup a mechanism that supports this type, http://localhost:8888/api/v1/plumbing_tools.json, of URL as well.

For this, we will add some code to the .htaccess file created in the introductory article to this series. Remember, using .htaccess files is not recommended for production environments, but it will serve us just fine for the purposes of our testing our Swift app. In your usual text editor, type in the following lines of code to the .htaccess file:
# Turn on the rewrite engine
RewriteEngine on

# Rewrite Rules for version 1.0.0 api
# ###################################
# Access to a single inventory item
RewriteRule ^api/v1/([^\/]*)[/]([^\/]*)[//.](html|json|xml) /v1/PlumbingAPI.php?method=$1&item_id=$2&format=$3 [L]
# Access to entire inventory
RewriteRule ^api/v1/([^\/]*)[//.](html|json|xml) /v1/PlumbingAPI.php?method=$1&format=$2 [L]
Any text after a pound character (#) is ignored by the interpreter of this file—it indicates a comment. The first non-comment line of code notifies the interpreter that we will be using rewrite rules. The other lines of code translate our clean url into a standard url that our web service can understand.

The syntax for the rewrite rule is as follows: RewriteRule Pattern Substitution [flags]. For the pattern argument we provided a regular expression (regex) to conduct the translation for us, as we would like to make it as generic as possible—in order to support multiple API signatures. The first RewriteRule interprets the single item with description inventory request for both copper pipes and fittings as well as plumbing tools. The second RewriteRule addresses requests for entire inventories. See this guide (.pdf) for more on regular expressions.

In the same file but just below the our last line, we'll now create the rewrite rules for version two of our API. Here are the rewrite rules for version two of our web service:

# Rewrite Rules for version 2.0.0 api
# ###################################
# Access to a single inventory item
RewriteRule ^api/v2/([^\/]*)[/]([^\/]*)[//.](html|json|xml) /v2/PlumbingAPI.php?method=$1&item_id=$2&format=$3 [L]
# Access to entire inventory
RewriteRule ^api/v2/([^\/]*)[//.](html|json|xml) /v2/PlumbingAPI.php?method=$1&format=$2 [L]
Save your .htaccess file and point your browser to the following url: http://localhost:8888/api/v1/plumbing_tools.json. The web service should respond by sending you the entire inventory of plumbing tools.

This url will also work: http://localhost:8888/api/v1/plumbing_tools/json. You can replace the json path with any other supported format.

Now point your browser here: http://localhost:8888/api/v1/plumbing_tools/pt12010.json. PT12010 is an item id value. This last web service request will respond by transmitting the relevant information along with description for the item matching the provided id.


Versioning
Placing web services with expanded or modified functionality into a separate folder is arguably the simplest versioning scheme to implement. There are other more complicated, and necessary, versioning schemes in use today. In our scheme, folder v1 is the earliest web service and v2 is the most recent. A number of arguments speak in favor of this implementation: there is no ambiguity about which web service version you are talking to, backward compatibility is maintained and you don't have to worry about creating dependency issues because each versioning folder contains the complete set of services.


Moving Forward
With that, we have completed our Super PHPlumbing Bros inventory API. Next week, we will move on to the final segment of this tutorial series and begin building the Swift client application that we will use to query the API and serve the content up to the end user. As always, comments, questions and suggestions are welcome below.



This project can be found on GitHub.

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.

Networking in Swift: Building a RESTful API in PHP, Part 1

This is the second post in our tutorial series on networking in Swift. If you followed along in the introductory article, you have installed MAMP on your local machine, created an .htaccess file and set up the basic file structure for the project. In this tutorial, we'll begin building the API for our Super PHPlumbing Bros web service.

This RESTful API in PHP will serve content to the Swift-based iOS client application we'll create in the final part of the series. Our API will perform five distinct tasks when queried. It will provide: 1) inventory items response logic for our Plumbing Tools; 2) inventory items response logic for Plumbing Supplies; 3) inventory item response logic for Plumbing Tool with Description; 4) Inventory item response logic for Plumbing Supply with Description; 5) Error response logic.

In this article, we will cover the structure of our API queries, provide a simple bare bones interface for the service, and then build the first half of our custom API to serve up our plumbing supplies inventory.

API Queries
Our application will communicate with the web api through a simple url scheme. If you are not familiar with url schemes, take a brief detour through the linked Wikipedia page to learn about how they work (simply memorizing the components of a url scheme outright will save you lots of needless lookups later).

Our first stab at a url scheme looks crude. Here is the URL scheme that we will use to access our entire inventory of plumbing tools: http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json.

Let's take a closer look at this scheme. Any text in a URL that comes after the question mark (?) is known as the URL query component. Each key/value pair that follows is logically separated by an ampersand (&). In this example the query string contains two key/value pairs. These key/value pairs will get passed along to our PlumbingAPI.php script via an associative array known as $_GET[]. Within our PHP script we will access the values for the 'method' and 'format' keys as follows: $_GET['method'] and $_GET['format'] would return 'copper_pipes_and_fittings' and 'json', respectively, in the crude example above. We use these values to determine what was requested of our API.

A Bare Bones API
Let's get down to it. Using your text editor, open PlumbingAPI.php for both versioning folders, v1 and v2. Until further noted, we'll be entering the same code in both versions. For the skeletal structure of our API, we are going to adapt the code from Mark Roland's helpful tutorial on "How to Build a RESTful API Web Service in PHP." We'll explain each component as we add flesh to our bare-bones script. Here's a Gist of the script:


After reading through the code, copy it into the PlumbingAPI.php file in your v1 folder. Using the URL scheme from above, point your web browser at http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json, and you will see the API's response to the given method and format:

Simple API call to bare bones script


If you now navigate to http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&format=json, you'll see the response from the plumbing_tools method:

Second API call to bare bones script
  
If this is not working for you, then go back and make sure that you followed all the steps. If you do see a response in your web browser, then congratulations! You've successfully built and deployed your locally hosted web service. The various responses from our api are made possible by the following conditional code structure, from line 120 to the end of the file above:
// Copper Pipes and Fittings API //
if( strcasecmp($_GET['method'],'copper_pipes_and_fittings') == 0){
    echo 'Copper Pipes and Fittings API Call. <br>';
}

// Plumbing Tools API //
else if( strcasecmp($_GET['method'],'plumbing_tools') == 0){
    echo 'Plumbing Tools API Call. <br>';
}

// ** Deliver Response ** //
// Return Response to browser //
deliver_response($_GET['format'], $response);
With the exception of the function definitions, our script is executed from top to bottom. Notice the conditional if else if structure here. In our first API call we passed in the value 'copper_pipes_and_fittings' for the 'method' key. Recall that the parameters of a query string are passed in to the $_GET[] global array, which we read from in our first conditional if check. Since it evaluates to true in the first API call, we fall in that conditional block and therefore echo "Copper Pipes and Fittings API Call", followed by the function call: deliver_response($_GET['format'], $response). This last function call is what prints out the second line in the browser.

In our second api call, we passed in the value 'plumbing_tools' for the 'method' key in the URL. With this query, we fell into the conditional else-if check above. This gave us our alternate response. That's all there is to it!

Moving forward, we'll build on top of this primitive structure of conditional checks followed with a response using the echo call.  For explanations of built-in methods such as  strcasecmp() and echo, check out php.net and search for those calls to get documentation along with code samples on how to use them.

Building the Supplies Interface
We'll now begin building out the control flow for the various tasks our API will perform. In the first if conditional control flow replace the code at line 122 (echo 'Copper Pipes and Fittings API Call. <br>';) with the following:
// build payload //
$response['code'] = 1;
$response['api_version'] = '1.0.0';
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
   
// if an 'item_id' was provided then return details for that item //
if ( $_GET['item_id'] ) {
    $response['item_id'] = strtoupper($_GET['item_id']);
    $response['data'] = copper_pipe_or_fitting_item_details(strtoupper($_GET['item_id']));
}
// else return our entire inventory of copper pipes and fittings //
else {
    $response['data'] = copper_pipes_and_fittings_inventory_without_description();
}
Save your PlumbingAPI.php file and point your browser to this URL: http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json. The response will appear as follows in your web browser:
Copper Pipes and Fittings Inventory without Descriptions.
Copper Pipes and Fittings Inventory.
Delivering Response. $api_response = Array, format = json
Your are seeing this response because our first if check did not fall through as we did not provide an 'item_id' key with an associated value pair as parameters in the query part of our URL. In other words, a parameter with this format, '&item_id=<some item id>', was not appended to the above URL. This resulted in our conditional control flow to fall through the else path. In this else block we call a method that we defined earlier: copper_pipes_and_fittings_inventory_without_description(). In our definition of this method, notice that we call another method: copper_pipes_and_fittings_inventory(). This last method is responsible for fetching our entire inventory of copper pipes and fittings along with all item details. Go to this method, found in lines 27 -33 above, and replace line 32 (echo 'Copper Pipes and Fittings Inventory. <br>';)<code> with the following:


This is an associative array of sub-arrays. Each sub-array contains all the information of one inventory item. There are twelve items in our hypothetical Copper Pipes and Fittings category, the information for which was cobbled together from online sources. In a real world scenario, this or a similar method would normally pull this data from a data store like a database. But for the sake of brevity we will skip this part. Now go to where we defined the method copper_pipes_and_fittings_inventory_without_description() (line 56 in the bare bones files above), and replace lines 57 and 58 with the following: 
return copper_pipes_and_fittings_inventory();
For now we'll simply return our entire inventory with descriptions. We will revisit this method later and write code to omit item descriptions. Now navigate to our response delivery function (function deliver_response($format, $api_response)), line 23 in the bare bones code, and replace its echo command in line 24 with the following:


The response to our API query gets processed here. If a parameter of 'format=json' is provided in the query part of the URL, then our script would fall through our first if check. This parameter informs our API that one of three available formatted responses was requested. We support three formats in this example: json, xml and html. 

Let's now write the code to process json format requests. In the first conditional if-check block (line 14) replace the comment (// JSON Response //) with the following code:
// Set HTTP Response Content Type //
header('Content-Type: application/json; charset=utf-8');

// Format data into a JSON response //
$json_response = json_encode($api_response, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

// Deliver formatted data //
echo $json_response;
Save your PlumbingAPI.php file and point your browser to this url, http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json. The response will appear as follows in your web browser:
{
    "code": 1,
    "status": 200,
    "data": [
        {
            "id": "CP12010",
            "name": "1 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_inch_copper_pipe.png",
            "description": "1 in. x 10 ft. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
        },
        {
            "id": "CP12020",
            "name": "1 1/4 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_1_4_inch_copper_pipe.png",
            "description": "1 1/4 in. x 10 ft. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
        },
    .
    .
    .
    .
        {
            "id": "CP14040",
            "name": "1 1/2 inch copper elbow fitting.",
            "image": "http://localhost:8888/assets/1_1_2_inch_copper_elbow_fitting.png",
            "description": "1 1/3 in. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
        }
    ],
    "api_version": "1.0.0"
}
The vertical ellipses indicate that we trimmed the actual response. You should see a lot more data in your browser. The problem with this response is that the copper pipes and fittings inventory response contains too much data. In our next step we'll trim the response so that item descriptions are omitted. 

It is not good practice to submit details of items when requesting them in bulk. In a real-world scenario, internet access is often spotty and unreliable. And serving up too much data could negatively impact your users' experience. And since users are often not aware that your application is not to blame for a given issue, but rather their connectivity to the network, they will associate this bad experience with your application. So, in an effort to mitigate connectivity issues, we should always prefer to send the least amount of data as possible over a network. Also, it is very unlikely that you can fit all this data for one item onto a screen when presenting the user with a list of items.

To omit item details, navigate to where we defined the method copper_pipes_and_fittings_inventory_without_description(), and replace our return command (return copper_pipes_and_fittings_inventory();) with this chunk of code:
    // pull our entire inventory of copper pipes and fittings //
    $inventory = copper_pipes_and_fittings_inventory();
   
    // container for inventory minus descriptions//
    $inventory_without_details = array();
   
    // iterate through inventory and duplicate all attributes except descriptions //
    foreach ($inventory as $key=>$value) {
        if (is_array($value)) {
            $inventory_item = array();
            foreach ($value as $subkey=>$subvalue) {
                if ( strcasecmp($subkey,'description') != 0 )
                    $inventory_item[$subkey] = $subvalue;
            }
            $inventory_without_details[$key] = $inventory_item;
        }
    }
    return $inventory_without_details;    
This code is straight forward. It iterates through the json objects and all the items into another container with the exception of key value pairs that are associated with a key name of 'description.' Save your PlumbingAPI.php file and point your browser to this url, http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json. The response will appear as follows in your web browser:
{
    "code": 1,
    "status": 200,
    "data": [
        {
            "id": "CP12010",
            "name": "1 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_inch_copper_pipe.png"
        },
        {
            "id": "CP12020",
            "name": "1 1/4 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_1_4_inch_copper_pipe.png"
        },
          .
    .
    .
    .
        {
            "id": "CP14040",
            "name": "1 1/2 inch copper elbow fitting.",
            "image": "http://localhost:8888/assets/1_1_2_inch_copper_elbow_fitting.png"
        }
    ],
    "api_version": "1.0.0"
}
Again, the vertical ellipses indicate that we trimmed the actual response. Notice that the descriptions have been omitted from the response. 

We will now write code to serve an individual copper pipe or fitting with a description. Find where the method function copper_pipe_or_fitting_item_details($item_id) is defined (line 66 in our bare bones API) and replace the two lines filling out the function (i.e. 67 and 68), with the following:
// pull our entire inventory of copper pipes and fittings //
$inventory = copper_pipes_and_fittings_inventory();
   
// container for item matching the provided item_id //
$inventory_item = array();
   
// iterate through our inventory and find the requested item //
foreach ($inventory as $key=>$value) {
    if (is_array($value) && strcasecmp($value['id'], $item_id) == 0) {
        foreach ($value as $subkey=>$subvalue) {
                $inventory_item[$subkey] = $subvalue;
        }
        break;
    }
}
return $inventory_item;
Save your php file and point your browser to this URL: http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&item_id=CP12010&format=json. This is an endpoint to the first item from our json inventory response above. You should see the response below:
{
    "code": 1,
    "status": 200,
    "data": {
        "id": "CP12010",
        "name": "1 inch copper pipe.",
        "image": "http://localhost:8888/assets/1_inch_copper_pipe.png",
        "description": "1 in. x 10 ft. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
    },
    "api_version": "1.0.0",
    "item_id": "CP12010"
}

Congratulations! We have completed the first half of our web API, serving up content for our copper pipes and fittings inventory. In the next article in the series, we'll complete the API to serve up our inventory of plumbing tools, and then begin building our Swift application to bring that content to our end user. Follow the line for part two on building a RESTful API in PHP.

This project can be found on GitHub.

As always, comments, questions, and suggestions are welcome below!

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. 

Networking in Swift: From the Backend API to the End User App

Introduction
In this tutorial series, we will create an iOS application that will leverage Swift's networking layer to query a custom-built web service. First, we'll build a RESTful API in PHP from the bottom up and host it on our local machine. Then we'll craft an iOS Swift application to consume the content provided by the service, and present it to the end user in a collection view. The series is intended for people who have some degree of programming experience, but who have not yet obtained much practical knowhow on building an everyday, real-world, user-facing, mobile application. 

A typical use case for mobile applications requires the consumption of content that is hosted on a web server. For successful mobile app development, this means that you not only need to know how to build an application that consumes web content, but also to have a high level understanding (at the very least!) of how a web service actually delivers content to your mobile application.

This is important because you will encounter network related errors during your development cycle. And if you don't have at least a basic understanding of the web service that your are trying to communicate with, then you cannot be sure where the errors are originating from. In addition, you will likely also be asked, at work or by your own clients, to begin writing a mobile application that relies on a web service that has not been built yet! (This actually happens way too often!) In such cases, you can write your own temporary web service that delivers mock data to your application, if you know how to build one. Although there are other ways of delivering such mock data, this can be just as useful. 

In this article, we'll provide an overview of the project, and then work through the preliminary steps for running the web service on our local machine. In the following articles, we'll build out the PHP script that will execute the API, and finally construct our Swift application to query the service and return the relevant data to the end user.

The ABCs of APIs
What is an API and how will our Swift application interface with it? API stands for Application Programming Interface. A simple web search for 'API' will return many definitions with various types of descriptions and creative examples. I like to think of an API as a real object. 
Source

Since the internet is a series of pipes and tubes, our API will provide an interface to a plumbing supply inventory. Let's call our API the Mario Interface. Mario works at the front desk of a plumbing supply house called Super PHPlumbing Bros Inc. Mr. Swift is a plumber who needs some supplies to rescue a local potentate's daughter from the clutches of an invading warlord.

Mr. Swift finds PHPlumbing and walks up to the counter where he encounters Mario. Mr. Swift tells Mario that he would like some piping, mushrooms and a wrench. Mario says, "No problem, but first I need you to know exactly what you need," and hands Mr. Swift two forms.

Each form is titled with the company's name. Below the title, there are several check boxes, but only one may be checked per form. The relevant check boxes are: Piping/Fittings and Plumbing Tools. Below that is a description field for the requested items along with their quantity. 

Once completed, Mr. Swift hands the forms to Mario, who then passes them along to his employees, local Toads from the Mushroom Kingdom, who are tasked to assist him. The Toads find the relevant items, bring them out and place them on the counter. 

If at any point during this process there was a problem retrieving Mr. Swift's supplies, the Toads are responsible for reporting these errors up the chain of command, from the assistants up to Mario and terminating at Mr. Swift.

In our analogy, Mr. Swift is the client (our iOS application) in need of content or plumbing supplies. Super PHPlumbing Bros Inc. is the store or website that has the supplies or content that Mr. Swift is looking for. The form for getting supplies is the actual url (location of content) that is used to find and retrieve the content. And Mario, along with the Toads, comprise the API. 

APIs, and people like Mario, are needed to maintain a system of flow control structures that are necessary to efficiently run the business logic of the operation. Can you imagine a plumbing supply house that had no control structures like forms and employees to manage its everyday workflow? The princess would be doomed.

In this tutorial series, we'll construct a RESTful API in PHP to serve up an inventory of plumbing tools and supplies, and then build a custom Swift app to interface with the API and serve that inventory to the end user. For now, let's get our local server up and running. 

Setting Up the Local Server
Unfortunately, the PHP file that will serve our API will not execute on its own. A service is required to interpret and execute our PHP script. We therefore need to set up a place on our local machine to host our Super PHPlumbing Bros. supply house. One of the easiest ways to get a server up and running on a Mac is with MAMP. Once you've downloaded MAMP, you can run the package by double clicking it.

After the package mounts, follow the instructions to install the software. 

Once installed, navigate to your Applications folder and start MAMP. You will be prompted with several initialization screens. Once MAMP is installed, start the server my clicking the START button in the top right corner of the application window. 


The tiny box to the right of the word Apache should turn green if everything went smoothly. This means that your server is up and running! Now start a new session of Safari, and in the url field type the following address: http://localhost:8888 You should see a similar screen to the following, which indicates that all is in working order:

.htaccess
A .htaccess file provides directory level configuration on how a web server handles requests to resources that are in the same directory as the .htaccess file itself. Note that using .htaccess is discouraged for production environments, but for the purposes of our tutorial, it should work just fine. Using your favorite text editor, create a new file and name it .htaccess. In the screen capture above, notice the directory path next to the text, “Document root:”. Mine reads: "Document root: /Applications/MAMP/htdocs." This is where your PHP file, along with all related resources will live. Place your .htaccess file in this folder.

Remember, any file name that begins with a period “.” is a system file and is hidden by default. To view hidden files, you can use the "ls -a" command in a terminal. To view hidden files in Finder, you can follow the instructions here.

File Structure 
Navigate to the folder that contains your .htaccess file. For me, it's /Applications/MAMP/htdocs, and create three folders with the following names: v1, v2, assets. More on these folders later, but for now, your folder structure should more or less look like the following:

Using your text editor create a new file and call it PlumbingAPI.php. This file models the Mario Interface, our counter guy. Place a single copy in folder v1 and v2. The v1 and v2 folder will be used for version control. The earlier versions of an API would typically reside in folders with a smaller number while the most recent API edition would live in the folder with the largest number.

Moving Forward  
With that, we're all set to go! In the next segment of the tutorial we'll build our RESTful API in PHP, so let's take the plunge. Or, if you want to skip ahead, follow the link to the tutorial segment on building our Swift client application.


Reverse Undercover: Get The Full Picture With "Sousveillance" Jacket


It's no secret that a variety of devices and their masters are going to be watching you every time you leave the house.  Instead of being infuriated or marginalized by this, why not use their own powers against them?  Now you can shoot first (well, photos, at least) with the new Aposematic Jacket.

As reported by wired.com, this new wearable technology protects not just with surveillance, but with the threat of it as well.  Welcome to the world of "sousveillance", taken from the idea that you are watching from below, not being watched from above (the "sur" in "surveillance.)  The Aposematic's South Korean creators, artists Kim Yong Hun and Shin Seung Back, stitched four working cameras (and eight dummies) onto a regular black blazer, daring any passersby to mess with the wearer.

The Aposematic, spotted in the wild.
(Image courtesy mashable.com.)

The Aposematic is named for the bright frogs and other creatures who use their overt threat of danger to ward off predators.  These days, too much information can sting worse than a dose of too much poison venom. Four cameras are triggered from a discreet button hidden in the Aposematic's sleeve, immediately offering a panoramic image which can be beamed to a website for realtime extreme exo-monitoring.  It's the ultimate selfie, plus a sort of security.  “Cameras make people act ‘properly,’ ” Kim says. “Once someone’s behavior is recorded, it will exist beyond time and space so that will have the possibility of being ‘judged’ by others anytime and anywhere.”

What're you lookin' at?
(Image courtesy pinterest.com.)

Kim raises serious questions about the state of our society and how surveillance/sousveillance now acts as a built-in behavior modifier.  He ponders, “How will people act when everything is recorded all the time? Will people have to always behave themselves? Or will we have to re-invent the concept of the ethics of humanity?”

Even though the Aposematic is an art project rather than a fashion movement, it makes it neatly known that accountability is for everyone.  We must first observe and affect our own surroundings before we can hope to do so with others.  We must be the checks and balances that the surveillance of the powers-that-be lacks.  Hopefully the changes that are enacted as we progress further into a surveillance society aren't just because someone is watching...they'll be because some people should have been acting better all along, and will shape up in a world where they have nowhere to hide.  And now, that includes the watchers too.

Bling bling, sousveillance is a thing.
(Image courtesy de.wikipedia.org.)



New App Scores You Great Restaurant Reservations (But Finding A Dinner Date Is Still Up To You)

There are a host of concierge-esque apps out there already, but sometimes you just want the one that's the butler with the black tie.  Now, a new app that has launched in New York, Boston, and L.A. is able to score you seats at the hottest eateries...all you have to do is be a little flexible.

According to travelandleisure.com, the new Reserve app was created by the inventors of Uber, to revolutionize your dining experience in much the same way they have turned random drivers into your personal chauffeurs.  Simply enter the desired reservation time, date, and party size, and Reserve scans for spots that'll satisfy.  Results that interest you will be updated in availability by text.

Reserve's ability to infiltrate the upper echelon of excellent eateries is aided by their request that your timeframe be somewhat flexible.  If you enter the option that you'd like to dine between 8 and 9:30 PM, the restaurants can better plan how to seat and serve all of their patrons, and can anticipate how to react most efficiently when they can assemble the best possible schedule.  This allows you to get into top-shelf spots without worrying that you're not cool enough to dine at the "right" time...they've got your info, and they'll let you know.

Helpful photos let you decide by decor, if that's more your style.
(Image courtesy reserve.com.)

You can even use Reserve to handle your bill beforehand, if you don't want there to be a fight over the check.  Credit card and tipping info can all be entered during the booking process, and a summary (along with a $5 booking fee) will simply be sent to your smartphone after the meal.  Things like your profile picture can help elevate service immediately onsite (you could feel like a pseudo-celebrity when you're recognized on arrival.)

Reserve is available for download here.  Other cities including San Francisco, Chicago, Washington D.C., and London are soon to be added to their well-curated culinary list.  Let technology worry about handling your reservations.  You just go handle the decoding of what you're going to wear.  And talk about.  And drink.  And food items to pronounce correctly in French...


You only want the best seats at the finest restaurant if you're going to indulge in serious culinary craziness, like fugu sushi.
(Image courtesy radiotimes.com.)

Electroadhesion: How Does That Grab You?

It's no secret that robots are fast taking over a variety of different manual labor jobs.  Yet their fine motor skills could use some refinement other than "clutch that thing" or "use suction to grab that thing."  Now, a new company is developing a means for robots to snag things using the principles of static electricity (which actually has uses other than rubbing your feet on the carpet to shock someone or sticking a balloon to your hair.)

According to theverge.com, the GrabIt company has created mechanical "hands" that use electrostatic attraction to lift and relocate objects.  Electrodes embedded on the gripper's surface or in its flexible "fingers" use the forces to delicately deliver everything from sheets of glass to crates.  Even particularly fragile tech items like an iPad are safe in static electricity's grip, and bruisable items like fruit or poppable bags of chips are also no problem for "electroadhesion."

One version of a GrabIt robot's grip ability.  It's bigger, flatter brother can pick up large crates.
(Image courtesy grabitinc.com.)

With no reconfiguration of gripper parts needed (as traditional grabber/sucker robots might require), the possibilities for electroadhesion are vast.  Check out GrabIt's website for a variety of videos of what their technology is capable of.  The machines' electrostatic surface area generates and maintains a great deal of well-dispersed power, making larger objects as easily handled as smaller or more delicate ones. The technology could even be applied to conveyor belts for an added level of factory security.

Best of all, the electroadhesion technology requires less power than traditional gripper robotics.  The GrabIt 'bots don't require expensive vacuum tubes or pumps, which is nice not only on the wallet but also on the ears (this technology is considerably more quiet than other types of grippers.)  It's small enough to be useful at home, but strong enough for factory work.  Could one of the most useful pieces of future robotics be a technology that's basically just giving everything an electrostatic hug?

Everything can use a little grabbing sometimes.
(Image courtesy thebusinessofrobotics.com.)



Can't Do Math? With This App, Your Problem Is Solved

Even some of the world's most intelligent minds balk when it comes to making numbers work.  Math equations filled with letters and strange symbols just don't add up for some people.  Now, for the numerically-challenged, a new app has been invented to be your own personal number-cruncher.

According to einfolive.com, the PhotoMath app works by analyzing a picture that you take of a printed equation.  It then shows you step-by-step how the equation should be properly dealt with, demystifying the mathematical process so that the user eventually may be able to apply the same principles sans smartphone.

For those without "A Beautiful Mind", now you can fake it.  Russell Crowe not included.
(Image courtesy theguardian.com.)

The process PhotoMath uses is called Optical Character Recognition.  First, it scans the desired text.  Then, it filters and enhances the equation's text, removing anything not required for the solution by extracting the equation's features.  Finally, the characters will be recognized by the app, and solved as you follow along.

The app works on a variety of math problems, including regular arithmetic, fractals, decimals, exponents, roots, and simple linear equations.  It cannot currently solve equations that are hand-written, but is able to deduce text coherently from standard printed pages.

PhotoMath works on Windows and iOS phones, with an Android version launching in 2015.  Ironically, the PhotoApp's amazingly useful features were created by MicroBlink, who were otherwise involved in developing photo recognition software that many malign as invasive and creepy when used for surveillance.  At least one good thing has come out of this cyber-scrutiny:  the ability to teach a useful life skill in simple steps.  If only all of technology's evil plans had such a good side.

It's basically this, except inside your phone.
(Image courtesy theoldrobots.com.)

Space Station Sunday: Spacewalks, Part III

Good morning, space fans!  Here's what's been up (260 miles up) this week.

A successful spacewalk, the third in as many weeks for the current ISS crew, was completed on Wednesday.  According to nasa.gov, Russian cosmonauts Max Suraev and Alexander Samokutyaev, who are both EVA (extravehicular activity) veterans, spent 3 hours and 38 minutes outside the ISS.

Cosmonaut Maxim Suraev has got this spacewalking thing down.  And up.  And sideways.
(Image courtesy nasa.gov.)

The two cosmonauts took photos, jettisoned old experiments and equipment, and collected samples for analysis of a mysterious growth on the exterior of the Russian modules (the substance is thought to be microbes or propellant residue...no word on alien gardening projects yet.)

Even if the substance did prove unpleasant, it's likely nothing the ISS astronauts haven't dealt with already.  Samples of MRSA, e.coli, and salmonella are among the pathogens that get studied in microgravity (where their structure and growth may be altered.)  Certain behaviors the diseases exhibit during their stay on the ISS could lead to different discoveries in combating them back on earth.

Speaking of back on earth, the unmanned SpaceX Dragon capsule (which had ferried supplies to the ISS in late September) has been returned to sender, chock full of completed science experiments.  It splashed down in the Pacific Ocean some 300 miles west of Baja, California, on Saturday afternoon.

"AIR MAIL!"  The SpaceX Dragon leaves the ISS, bound for Baja.
(Image courtesy nasa.gov.)

The Dragon, which had carried up a Rapid Scatterometer (for use in earth science monitoring) as well as a 3D printer, carried back gear that was just as important.  An arugula plant growth study was undertaken to examine how plants might be grown to optimum nutrient-density in microgravity environments (which could be a big help on future long-distance spaceflights.)  Another experiment, the Rodent Research-1, aided in the understanding of how microgravity affects various biological functions. 

Sam Scimemi, director of the International Space Station division at NASA Headquarters, stated, “This mission enabled research critical to achieving NASA’s goal of long-duration human spaceflight in deep space...Investigations in the returned cargo could aid in the development of more efficient solar cells and semiconductor-based electronics, the development of plants better suited for space, and improvements in sustainable agriculture.”

Even more good gear is expected to reach the ISS soon, with the launch of a Cygnus spacecraft aboard an Antares rocket on Monday.  The Cygnus, an unmanned cargo craft developed by NASA-contracted Orbital Sciences Corp., will launch from the Wallops flight facility in Virginia, bearing nearly 5,000 pounds of payload.  According to NASA, it contains "science experiments, crew provisions, spare parts and experiment hardware."  It will arrive next Sunday after a "grapple" with the ISS's Canadian-made robotic arm, the "Canadarm", manned by astronauts Reid Wiseman and Barry Wilmore from the ISS cupola (that's the cool room with all the windows.)  This Cygnus upholds a NASA tradition of being named for a previous astro-adventurer, and is thus dubbed the SS Deke Slayton, after the Mercury 7 astronaut and Apollo-Soyuz Test Mission crewman.

More news to follow next week, as the Cygnus and other cargo vehicles arrive!  Maybe one of them will ferry up a delivery of some well-deserved Halloween candy, like a reverse trick-or-treat.  Until then, watch this space!  

The view from the ISS cupola, as captured this week by astronaut Alexander Gerst.
The green glow is the aurora borealis, which Gerst said was "completely engulfing us" before the sun appeared.
The captivation of the cupola is constant, for obvious reasons.

Shots Fired? New "Yardarm" Device Reports Police Weapon Use And Location In Real-Time

Police violence, no-knock raids, SWAT invasions, traffic stops gone wrong...all sorts of issues seem to arise these days between citizens and those who supposedly "serve and protect."  Weaponry, which has been made available to local police departments on an unprecedented scale, plays a major role in this.  Since America's glorious Constitution isn't about to let guns go out the window for police nor citizens, it's imperative that a middle ground be reached where our taxpayer-endorsed police forces can be held accountable for their firearm actions with official evidence (and the "body cameras" seem to keep mysteriously losing batteries.)  So, meet the Yardarm.

The Yardarm chip, shown in green, is a witness who can't lie.


Currently in development in Silicon Valley, the Yardarm is a startup venture that could start a serious new trend of keeping cops in check.  Installed in the butt of a pistol, the Yardarm's Bluetooth sensor connects to an officer's smartphone, then notifies police dispatchers when and where an officer carries, draws or fires their weapon.  It can even deduce the direction of the discharge, which could be important later in court for all parties involved.  In the officers' aid, it could help alert dispatchers when a cop is under fire but cannot immediately radio their situation or location.

Yardarm's website states their technology is "designed to seamlessly integrate into existing computer aided dispatch (CAD) and real-time crime center (RTCC) solutions", which provide maps for a dispatcher to track progress on. This could enable more accurate data regarding crime-infested areas and ultimately prove safer for everyone.

Unfortunately, there are no current plans to make Yardarms for nightsticks.


Fresh Crops From Water Drops: Spilling The Dirt On MIT's Soil-Free CityFarm

With city populations escalating abundantly, it's a challenge for futuristic farmers to figure out how to feed everyone with fresh ingredients.  Now, researchers at MIT believes they have solved this quandary, using an innovative new system that they call CityFarm.

As reported by nationswell.com, the soil-free CityFarm project uses hydroponic (water flow) and aeroponic (water misting) systems to grow a collection of crops, leaving the price tag and messiness of soil out of the urban equation.  Inventor Caleb Harper constructed a 7' by 30' plastic box in which he uses "pre-made weather" and is able to constantly monitor the plants' development, which is prodigious.  Thanks to the artificial light and carefully-calibrated plant care, CityFarm can grow enough food for 300 people in a single 30-day cycle.

Not only is the farm efficient and bountiful, it also saves resources.  CityFarm's method of growth uses up to 90% less water than conventional methods.  Harper believes eventually this could lead to a 98% reduction in agricultural water usage (making it ideal for water-deprived areas), as well as escalated nutritional value from the lack of pesticides and other soil contaminants.  CityFarm currently grows tomatoes, lettuce, and herbs in their successful style.

Pesky pesticides have nowhere to hide, as the plants' roots are fertilized with nutrients in water.
(Image courtesy tribeawesome.com.)

“No one has proven an economically viable model for these kind of plant environments,” says Harper. “What I’m trying to do is kind of be the Linux for these environments — the person that creates the common language for this new area of food production.”

Harper's plans don't stop at just the idea of the farm being like programming for a computer.  He actually wants to create a program, in conjunction with MIT, that will act as "plant operating system software."  This could be launched at other locations, such as an upcoming new attempt in Detroit, or it might help to regulate CityFarm's new plans to build vertically.  A similar project is already underway in Japan.  According to their website, CityFarm's technology combines their hydroponics/aeroponics with 
"novel environmental, diagnostic and networked sensing, control automation, autonomous delivery and harvest systems, data driven optimization and reductive energy design." Their high tech management along with their high yield of crops could be extremely beneficial for people living in any environment.

The CityFarm website proudly extolls their multifaceted workforce, including "engineers, architects, urban planners, economists and plant scientists." If other cities and towns can adopt CityFarm's "grow it HERE and eat it HERE" mentality, a host of jobs as well as tasty meals will be aiding the new urban infrastructure. Who knows what ideas such a locally-laudable system may spout next?

A serious salad bar is brewing at MIT.
(Image courtesy mitcityfarm.com.)