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.