Monthly Archives: April 2016

Programmatically add a Navigation Controller to your project

objective C demo
swift 3 demo






The whole idea is that your window strongs UINavigationController, and UINavigationController strongs your main ViewController.

The UINavigationController is set up in your AppDelegate. Then your UINavigationController is init-ed with your main view controller.


Then, in your main view controller, use self.navigationItem to set up the buttons and title.



First we create a UINavigationController property.

Then, we create the UINavigationController and init it with the main view controller of your project.
Set the UINavigationController as the root view controller of our window.

In your main view controller, make sure in your viewDidLoad, you set the navigation button like so:

The nav button has a button responder:

This means when you click on the nav button, we want to navigate to a new view controller. Hence, let’s implement the view controller that we want to navigate to.

File >> New >> File >> Cocoa Touch Class

Put in AddViewController for the “class name”.
Put in UIViewController for the “subclass of”.

Then import AddViewController to your main view controller, and implement the button responder like so:

Make sure you set background color for every view controller because if its default as clear, there may be animation issues.

@public, @private, @protected (objc)

ref –

The @public, @protected, @private are called accessor modifiers. They provide access visibility to the instance variable.

So we declare 3 iVar using @public, @protected, @private.

We then declare a child class, and declare MyFirstClass as a parent class.

The basics are laid out here.

  • @public iVars CAN be accessed by the child class
  • @protected iVars CAN be accessed by the child class
  • @private iVars CANNOT BE accessed by the child class

Since we do not provide any accessor methods via properties, the instance varaibles are not accessed via the dot notation (.)

Rather, they are accessed through the arrow ( -> ).

enforce the use of accessors

Say a developer writes a class, then write properties and accessors. However, what if some other developer goes

xcode 4.x+ automatically puts @private in the template for an object. Thus, you don’t have to worry about other people accessing your instance variable with the arrow and modifying unexpectedly.

The only way to modify the instance variables, is through your property methods.

NSURLSession – Out of process upload/download

ref –

demo project

Background Uploads and Downloads

Adding support for background uploads and downloads is surprisingly easy with NSURLSession. Apple refers to them as out-of-process uploads and downloads as the tasks are managed by a background daemon, not your application. Even if your application crashes during an upload or download task, the task continues in the background.

Enabling background uploads and downloads is nothing more than flipping a switch in your session’s configuration. With a properly configured session object, you are ready to schedule upload and download tasks in the background.

When an upload or download is initiated:

  1. background daemon comes into existence
  2. The daemon takes care of the task and sends updates to the application through the delegate protocols declared in the NSURLSession API
  3. If app stops, daemon continues task
  4. If download task finishes, daemon informs session.
  5. The session then invokes the appropriate delegate methods to make sure your application can take the appropriate actions, such as moving the file to a more permanent location.

When the Background Transfer Service gets in action, what is actually happening is that the operating system takes charge of all the download process, performing everything in background threads (daemons).

While a download is in progress, delegates are used to inform the app for the progress, and wakes it up in the background to get more data if needed, such as credentials for logging in to a service. However, even though everything is controlled by the system, users can cancel all downloads at any time through the application.

A reminder that a block parameter has 3 parts. The return, the parameter, and the block name. Like so:

So this means that the block is used where it takes 2 doubles, and does not return anything. It is called by using the block name ‘block’.

Handle Events for Background Session

Apps that (using an NSURLSession with a background configuration) may be launched or resumed in the background in order to handle the
completion of tasks in that session, or to handle authentication.

In other words, when an app uses NSURLSession with background service (whether its a GET request or downloading/uploading), NSURLSession needs to let the app know and to handle the completion of tasks for that session.

We simply strong the completionHandler block in order to call it later to let the system know that we complete all tasks.

NSURLSessionDelegate’s PROTOCOL METHOD will be called. In there you access the appDelegate and call the completionHandler.

Hence when you’re using it, if an application has received an -application:handleEventsForBackgroundURLSession:completionHandler:
message, the session delegate will receive this message to indicate
that all messages previously enqueued for this session have been

Declare the session completion handler member variable:


Then, have its set property copy the completion handler:


Go to your ViewController and conform to NSURLSessionDelegate.

This is so that we need to implement URLSessionDidFinishEventsForBackgroundURLSession.

Now when your session object’s delegate queue tasks have all been processed, in your AppDelegate, you will receive a
application has received an -application:handleEventsForBackgroundURLSession:completionHandler:
message and your protocol method

will be called.

Then your session delegate will send a message to protocol method URLSessionDidFinishEventsForBackgroundURLSession to indicate that all messages previously enqueued for this session have been

Hence that’s why its the job of your URLSessionDidFinishEventsForBackgroundURLSession method to simply call the completionHandler and clean it up.

If your session delegate sends a message to call protocol method:

for authentication purposes, then you need to something similar. Where you give authentication information, then call the completionHandler().

Prepare the UI

Configuration Object

Session Object

Updating download progress percentages

When you resume a download task

Send last message related to a specific task

When your download have completed

NSURLSession basics

ref ––mobile-21394–mobile-21581

1) Simple GET of data

2) Downloading a file using NSURLSessionDownloadDelegate protocol

So we want to download a file. However, we want to see what percentage we are at, as well as when the file has finished downloading.

A session configuration object is nothing more than a dictionary of properties that defines how the session it is tied to behaves. A session has one session configuration object that dictates cookie, security, and cache policies, the maximum number of connections to a host, resource and network timeouts, etc.

Once a session is created and configured by a NSURLSessionConfiguration instance, the session’s configuration cannot be modified. If you need to modify a session’s configuration, you have to create a new session. Keep in mind that it is possible to copy a session’s configuration and modify it, but the changes have no effect on the session from which the configuration was copied.

Once a session is created and configured by a NSURLSessionConfiguration instance, the session’s configuration cannot be modified. A SessionConfiguration is immutable. If you need to modify a session’s configuration, you have to create a new session. Keep in mind that it is possible to copy a session’s configuration and modify it, but the changes have no effect on the session from which the configuration was copied.

  1. Use a private UIImageView to hold the image
  2. privately conform to NSURLSessionDownloadDelegate protocol
  3. Implement protocol methods

Add the image holder to your view hierarchy

Then use a NSURLSession to get a task running

Notice that we first get a default Session Configuration object. Then we pass it into the session to be used.

Configuring a session configuration object is as simple as modifying its properties as shown in the example. We can then use the session configuration object to instantiate a session object. The session object serves as a factory for data, upload, and download tasks, with each task corresponding to a single request.

Finally, implement the protocol methods

Make sure you use the main queue, to update your image holder with the data you just downloaded.

Also, if you are to use a progress view to show updates on progress, make sure you dispatch a code block onto the main queue, so that the main thread can run the code and show it.

concurrency, asynchronous, parrallelism

ref –

Concurrent and parallel are effectively the same principle as you correctly surmise, both are related to tasks being executes simultaneously although I would say that parallel tasks should be truly multitasking, executed at the same time whereas concurrent could mean that the tasks are sharing the execution thread while still appearing to be executing in parallel.

Asynchronous methods aren’t directly related to the previous two concepts, asynchrony is used to present the impression of concurrent or parallel tasking but effectively an asynchronous method call is normally used for a process that needs to do work away from the current application and we don’t want to wait and block our application awaiting the response.

For example, getting data from a database could take time but we don’t want to block our UI waiting for the data. The async call takes a call-back reference and returns execution back to your code as soon as the request has been placed with the remote system. Your UI can continue to respond to the user while the remote system does whatever processing is required, once it returns the data to your call-back method then that method can update the UI (or hand off that update) as appropriate.

From the User perspective it appears like multitasking but it may not be.


It’s probably worth adding that in many implementations an asynchronous method call will cause a thread to be spun up but it’s not essential, it really depends on the operation being executed and how the response can be notified back to the system.

Concurrency vs Asynchronous


There are various different ways of accomplishing concurrency. One of them is parallelism–having multiple CPUs working on the different tasks at the same time. For example, its like having more than 1 chef working on 5 recipes AT THE SAME TIME.

But parallelism is not the only way to achieve concurrency. Another is by task switching, which works like this: Task A works up to a certain point, then the CPU working on it stops and switches over to task B, works on it for a while, and then switches back to task A. If the time slices are small enough, it may appear to the user that both things are being run in parallel, even though they’re actually being processed in serial by a multitasking CPU.

A characteristic of task switching is asynchronous. Asynchronous is when a task DOES NOT BLOCK the worker, and the worker is free to work on other parts of other tasks.

Asynchronous is when a chef is working on 5 dishes at the same time. Going through steps of each recipes one after another WITHOUT IT WAITING (or blocking in IT terms). The chef does not let the recipe step BLOCK HIM from moving on to other recipe tasks.

For example

He preps dish 1, apple pie. then puts it into the oven for a 1 hour bake. Now, the baking process DOES NOT BLOCK him from working on other recipes. So that he does not waste time waiting on the oven, he moves on to other recipe(s).

While dish 1 bakes, he moves on to dish 2, which to chop up some Potatoes and salt some beef chunks. After the potatoes are prepped, he throws them into a pot and starts simmering them with some beef chunks. The simmering process DOES NOT BLOCK HIM from moving on to other recipes. Thus, he is free to move on to other tasks of other recipes.

He then moves on to dish 3, which is to simply toss some salad. He is done with dish 3.

He then goes on to dish 4, which to boil some pasta. Fire on high and the water warms. The boiling process DOES NOT BLOCK him from working on other recipes, so he moves on.

For dish 5, he just chops some fruits and throws yogurt on top. Done!

Dish 4 (al dente pasta) water has now boiled and it DINGS our chef so he knows. He then comes back to Dish 4, salts the water, then throw in pasta. The pasta needs to cook for a few minutes. This cooking process DOES NOT BLOCK him, so he moves on to other dishes.

All Dishes are not processing in some way…so the chef now waits. After a few minutes, Dish 4 (pasta) finishes boiling. It DINGS the chef to let him know. The chef takes the pasta out and finishes preparing for it.

Now, the chef has nothing to do and waits for the next DING.

After an hour, dish 1 finishes baking and DINGS him. Letting him know that dish 1 needs attention. The chef goes to dish 1, takes out the apple pie..puts some vanilla ice cream on the side, and done.

He now has nothing to do and waits. Then after another hour, dish 2 finishes simmering and a timer DINGS him. He then slowly spoons out the morsels, chops some parsley, and finishes dish 2.

So as you can see, asynchronous means that there is one worker, one process, one chef…but its working on multiple tasks.

No task is holding on to him. Whenever he hits a point of a recipe where the recipe needs to take some time (bake, simmer, boil..etc), then he moves on to the next recipe’s task.

In IT term, asynchronous-ness is the ability to NOT stop on a task which depends on an external system (like reading a file from the file system, or loading data from the internet) and continue the processing of the application.