Basics of iOS Networking – Swift Style

Networking in the mobile context largely entails communicating with external entities over the internet. Like most modern web or mobile platforms today iOS supports HTTP.

These network requests are referred to as ‘Tasks’ in the iOS world and there are three basic network tasks you can perform using the NSURLSession API

Data Tasks – These are network tasks where you exchange simple data which typically get stored in memory as a NSData object during server interactivity

Download Tasks – These tasks involve retrieving the contents of a url as a temporary file from a server (supports running as a background activity)

Upload Tasks – These tasks handle similar messages as the download tasks just in the opposite direction by uploading files to a server (also supports running as a background activity)

This API is asynchronous and provides what some might liken to callbacks in Javascript. The example below is a data task (indicated by ‘dataTaskWithRequest’)

Screen Shot 2016-02-11 at 5.26.25 PM.png

‘in’ signifies the beginning of the completion handler block. This call can’t actually be kicked off without calling resume method on the task

data refers to the actual data you expect back and looks like byte stream data when you get the service response. This needs to be deserialized which you can do like below

Screen Shot 2016-02-11 at 5.21.43 PM.png

response gives you details about your response such as status code and such

error gives you detail if there is an error. If there is none you can expect it to be nil. data is nil if an error is returned

This is not the all in all you need to know on iOS networking but at the very least it should give you a thousand foot view of what you need to know make very common network calls in iOS using Swift.

One last point to note. By default iOS limits regular HTTP calls favoring HTTPS calls out of box. So you need to account for extra steps to support network calls to urls that are prefixed with basic HTTP.


Delegates in Swift

Delegates in Swift are pretty cool. They work sorta like how inheritance works except that the actions a delegate can carry out are scoped rather than a default inheritance of all attributes or capabilities of the delegator.

One analogy is the President having a delegate to the UN. The delegate can carry out a set of actions on behalf of the President, but can’t really do everything the President can. A delegate is not an instance of what it represents.

The official Apple docs describes Delegation as “a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type.”  One such a example is AVAudioRecorder , where a class that uses its instance to record audio can’t tell when it is done recording unless it’s a delegate.

AVAudioRecorder  uses a protocol to define what a delegate can know and do. As the source code shows below

public protocol AVAudioRecorderDelegate : NSObjectProtocol {

    optional public func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool)

    optional public func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) … 


By simply specifying my controllerView as a delegate I can now tell when recording is done

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {

    var audioRecorder:AVAudioRecorder! ….

    try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])

    audioRecorder.delegate = self

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {




Now your instance of one class type can carry out activities and responsibilities of another class. You go Delegate!

see more:

How to Alter the Speed of an Audio File in Swift

Assuming you figured how to play an audio file in Swift, now you want to play with the speed of the audio. The rate property of the AVAudioPlayer object is what you need to change up the speed. The catch is that you need to set the enableRate property to true before you can actually do this.

Screen Shot 2016-02-02 at 5.25.11 PM.png

In this example I create a helper function to set things up. audioPlayer is my instance of AVAudioPlayerI set currentTime in my use case to start the audio from the beginning. It is also a good practice to stop the audio before playing.

Screen Shot 2016-02-02 at 5.18.17 PM.png

Then I call that function in my actions

Screen Shot 2016-02-02 at 5.18.29 PM.png

That’s it mainly.

A month with Swift and iOS Development

I never would have imagined I would touch iOS development. I have been an avid Android user since the birth of the Samsung Galaxy series. Actually, I was led down that path mainly because my experimental jailbroken 3gs iPhone was buggy. I had the last of it when the glass shattered on a vent and had trouble replacing the glass myself. I never thought I would be back to an iPhone. Besides, Android devices are just more open and allow for easier experimentation.

Enter 2015 when I thought I would give the iPhone another try after 5 years of hating. The iPhone 6 is a nice design. I was intrigued about the experience of a seamless experience across multiple form factors and I have somewhat liked what I have been my Mac, iPad and iPhone. I still think the notes app sucks (so glad google keep is now on iOS).

Having done quite a bit of Android dev and mobile dev using PhoneGap in its early days, the thought of using Objective-C was scary enough for me to never consider iOS development. That all changed with Swift. I have grown to love the expressiveness of languages like Ruby and Python. Any language that follows a similar form is sure to catch my attention. Swift has done just that.

It is not quite as flexible as Python, my go to prototype/hack language, but for a mobile development and on iOS Swift feels like a home run. I actually enjoy doing this now and finally gave the development tools that Apple provides a chance. I am one happy customer. The idea of writing this post really came from a Udacity course I’m currently going through titled Intro to iOS Development with Swift. I would highly recommend it for anyone looking to get their feet wet.

All in all, I like Swift and development for my iOS devices is now an exciting endeavor I never thought I would embark on.

My 2016 Challenge (1 min read)

Credit – Vodafone Medien

So, Mark Zuckerberg recently shared his 2016 challenge. Apparently, he takes on something new every year and it got me inspired.  Making focus a priority is a goal of mine moving forward in life and it seems well fitting to articulate what had been brooding in my mind to take on in 2016.

My challenge in 2016 is to make my home sentient. I spend a lot of a quality time in my home and it only makes sense for me to enrich the experience. I’m not sure what this end point really looks like – Jarvis from Iron Man? Maybe not but, I know my interest is to start with capturing key information around my home like power usage and internet bandwidth usage to be more aware of what’s happening in the home. Measure such things as temperature, humidity and presence detection. This is also so my home can intelligently respond to my living experience. Essentially, me learn about my home and my home learn more about me.

I already started some work around power usage monitoring and will be sharing what I have learned as well as my journey to make a smart home. Yes, that’s the word. I expect this will have varying elements of IOT, Big Data, Machine Learning and Deep Learning. All areas I have been looking forward to take a deep dive into.

I intend to write a monthly blog reflecting on my journey in between more technical blogs highlighting what I have actually done. You are welcome to tag along.


Wrapping My Mind Around Docker

**Finally decided to put this up after I writing it up a year ago. Sure hope someone finds it useful though slightly outdated**

It is amazing to see how quickly Docker has picked up pace in the tech industry with a lot of momentum in its sails for years to come. It is early and a great time to get on board. There are so many resources out there describing what Docker is, but so few articulate it as well as Nigel Poulton on Pluralsight (Docker deep dive tutorial). In fact I credit all descriptions here to him. I will not be one bit offended if you stop reading here to check out his tutorial and never come back here.

My aim here is to try to describe 4 key components that are core to Docker : The Docker Engine, Docker Images, Docker Containers and Docker Repos/Registry. This is part of my attempt to wrap my mind around this technology.

If you have perused the web on what docker is you probably may have come across the dockyard analogy. After a while it gets kinda boring to hear just one analogy, but it’s amazing to see how perfectly it describes it. The descriptions here do tag along this analogy, but also attempts to break each component down using simple words.

The Docker Engine

This is also referred to as the docker daemon. In the shipping analogy, think of the docker engine as the shipping yard. Essentially, it is a program that provides standardized app infrastructure and runtime dependencies needed to run containers.  So if you think about this in the context of the analogy. The shipping yard has standard cranes, paths and machines which hardly ever vary from dock to dock. So a worker who goes to another shipping yard even in a different country should easily be able to operate the machinery upon arrival because the infrastructure is standardized and optimized to ship containers. This is how docker provides portability.

The Docker Image

This is the manifest in the shipping analogy. Essentially, it is a static or frozen version of a container that contains data and metadata needed to fire up a container. Typically a manifest describes what is being shipped and probably comes with instructions on how to handle the shipment.

The Dock Container

Well this is where the goods go in. Simply put, it is the running instance of an image. It is a light weight instance of linux

Docker Repositories and Registries

The best way to think about this really is the Apple app store or Google play store. Think of each app as a repo and the app store as the registry. Better yet, you can also think of this in terms of Github as the registry and the repos, well as repos. The thing to keep in mind here is that some images are verified and not all images can be trusted. Images which don’t require user prefix (like Ubuntu, Nginx, Mongodb etc ) have usually been verified by the docker team. Said more formally repos are where images are pulled from and registry is where images live (docker hub being the default)

I know this was not deep and comprehensive. I can share more on what I have grasped so far, but I’m not expert by any means. I do hope you are one step closer to nailing down this technology. Now go check out Nigel’s tutorial.

How Secure is Your Consumer Mobile App?

We are in a new frontier in the mobile security space. Mobile advances are happening at a rapid rate and with the arrival of wearables and the Internet of Things (IOT), standard mobile security practices have not quite kept up with the pace. Mobile is increasingly becoming our primary interface to the web and our means of exchange (ideas, experience, money etc). Fondness with our mobile devices makes it so easy for most to expose sensitive information even if this is just on the device and not on the web or social media. At the center of this mobile experience? The app ecosystem. So, how secure are these apps that simplify our daily activities?

Gartner has stated that roughly 75% of all apps will fail basic security tests through the end of 2015. So, think 3 out of 4 apps you use. It is presumptuous for any business or organization that makes or provides mobile apps to think that simply applying traditional web application security principles is sufficient. Mobile apps are significantly different than web apps in a number of ways. For one, deployment of an unsecured app feature is hard to take back. Once users have the app on their devices you cannot simply force a user to upgrade. With web, changes can happen behind the scenes and customers get the latest update when next they visit the website.

Securing mobile now requires going beyond traditional user facing security measures like password encryption, use of SSL (https) or data encryption. The mindset has to shift to App Integrity. This is because reverse engineering an unprotected app is pretty easy today. You can easily decompile most apps using free or cheap tools in less than 5 mins. And be able to see business logic and sensitive data in no time. Other than the potential for IP theft, malware insertion is a possibility. This could be a simple case of a reverse engineered app, in which malware is inserted with the app repackaged and deployed to 3rd party app stores. Jailbroken and rooted devices would be must vulnerable here. Can more be done? Yes.

Techniques like Anti Tampering Mechanisms, Code Obfuscation, White-box Cryptography (Obfuscating mobile native code, like C/C++, containing sensitive logic), Jail Break and root detection, Self Checksums are just a few ways to further harden an app. There are tools in the market that help with this, but it is vital to remember that hackers also have access to these tools and so it is critical to always add your own flavor of hardening.

In most cases, hackers given enough time, tools and motivation can almost certainly compromise your mobile app, but the goal here is to significantly reduce that risk by increasing speed bumps. This makes it even more critical to secure backend services or APIs with such things as token based authentication (ex: OAuth 2.0) as the next line of defense. It is important to consider how secure your app is because your customers security is vital to your business. So, do you know how secure your app is today?

How to Improve Comprehension Using a Simple Speed Reading Technique

Living in the information age means we get bombarded with a lot of it on any given day. Some information is less important than others and for that which is important it is natural to spend more time and slow down to better comprehend and recollect what is read. So how in the world will a speed reading technique help with better comprehension?

Well, first it is important to note that speed reading the right way is not simply about reading more words in a shorter time. Speed reading the right way fundamentally focuses on extracting the key ideas and message of what we read with more ease. #Ideas over words. Here is where the speed reading technique of pre-view makes a huge difference.

The power of pre-viewing a reading material plays on the fact that you can prep your mind for the material you are about to read. Have you ever been doing research on a car model and suddenly you observe that specific model everywhere you go? It seems like they came out of the woodworks. Pre-viewing has a similar effect. It places anchors on your mind on important detail so that as you read you key in on those critical ideas and make mental notes of them.

Pre-viewing will slightly vary depending on the material you are reading, but it largely consists of

  • Paying attention to the title (What are you about to read?)
  • Reading through the Table of Contents and glancing through the index of a book (pay attention to new words or high frequency words in the index)
  • Reading the 1st paragraph and last paragraph of the article or of each chapter (if a book)
  • Reading the the 1st and last sentence of each paragraph of a web article
  • Scanning through pictures, diagrams, headings, bullet points and italicized or bolded words
  • Reading questions at the end of each chapter for instructional books
  • For readings that require more facts asking the 5Ws & H (What, Who, When, Where, Why and How)

That simple exercise can take anywhere from 3 mins for an article to 15 mins for a book. The small time investment helps to identify what is really important in what you are about to read. Giving you the chance to focus in on those key concepts or takeaways to help with better comprehension as you read. Not only do you figure where to spend more of your reading time, an added benefit of pre-view is that you can quickly figure out if it is worth a read at all.

All writing has some measure of fluff. We just need help figuring out what is not fluff as quickly and as easily as possible, to better comprehend what we are reading. Pre-viewing helps with this, in addition to giving you a way to read any material faster. There is a lot more you can do to help with comprehension, but you will find this small tip go a long way. Give it a try today.

3 Things to Consider before Versioning your API

The question of how to version your API is one with varied responses depending on who you ask. But, often times we probably jump the gun on this. A couple of things drive API changes and each may require a different approach to handle the scenario. Let’s look at a few

New API Attributes

This is straight forward. You need to add new attributes to your API. Instead of versioning your service all you need to do is make the new attributes optional. The documentation captures this change and your API is backward compatible for older apps or clients. No big deal here.

Attribute Deprecation

This situation is quite different from the first because removing a required attribute will break older clients which you don’t want. This situation requires more of a social solution than a technical solution. Just give your clients a time frame for which the attribute will be supported and communicate it clearly, using documentation, your website and social media.

A combination of this and the first approach can be seen as an expand and contract approach where you may add a new attribute which might replace two other attributes (expand) and then remove the two older attributes at a predetermined time (contract).  These scenarios once again allow you get by without API versioning.

Resource Creation

Maybe the changes you are about to make actually imply a new and different API after all. It could be a new resource created to handle some level of aggregation required in certain scenarios. Which ever the case, new resource creation is what is called for and not API versioning.

If none of these scenarios really meet what you are trying to accomplish it is possible you do need to version your API. Different approaches to doing that will be discussed in separate post. At the very least, it does make sense to pause and reflect on the end goal. What else do you consider before deciding to version for your API?

Lessons From the ‘The Power of Habit’ by Charles Duhigg

This is probably one of the most impactful and practical books I went through in 2014. Everyone knows a thing or two about habits: good and bad. Just how exactly do you form a habit or break a bad one?

The author starts off by laying out the habit loop

Cue -> Routine -> Reward

Essentially, some cue initiates a routine, with some reward afterwards which makes the outcome of the routine satisfying. Cravings are what power this loop.

So basically, to create a new habit you just need to find an obvious cue and clearly define a reward. An example could be: lay out your gym clothes by your bed, so you wake to see it when you wake up in the morning (Cue). Go running (Routine). Drink a smoothie after your workout (Reward). You can fill in the blank, but that’s the basics of building a new habit.

Overcoming a bad habit? A little trickier. We need to first understand what craving is driving that specific behavior. Sometimes, it’s about remaking the habit by leaving the cue and reward as is, but changing the routine. This could be taking fruits to snack on when the craving for vending machine junk comes on around 3pm.

Interestingly enough the author highlights how personal belief, group support and accountability goes a long way. Want to stick with your new workout habit, get a workout partner.

Sometimes, breaking a bad habit can me more elusive and it’s critical to make sense of what craving is driving the habit loop. So these steps help

  • Identify the routine: The habit itself
  • Experiment with different rewards: To identify the craving
  • Isolate the cues: To Identify the cue by Paying attention to:
    • Location – Is this habit usually triggered at a specific place?
    • Emotional State – Is there a feeling that usually precedes the routine?
    • Time – Does this habit usually occur at a specific time of the day?
    • People – Are there specific people around you when this habit is on display?
    • Action – Is there a specific action that precedes the urge?

Being more aware of what makes up the habit loop goes a long way to tackling any habit. So, go ahead and take the first step towards breaking or making that habit.



Create a free website or blog at

Up ↑