On my work, technology and related stuff....

About me

Hi, I am Priya Rajagopal- a technologist, software architect and developer. I have worked on a wide range of technologies in my career. My current passion is mobile development. The notion of a customizable and powerful computing platform in the palm of your hand (literally) is very exciting.
Read more..

What else?

No comments

REST has been growing in popularity as the preferred way of publishing and consuming web services. REST has its origins in 2000 when Roy. T. Fielding introduced an architectural style and design for network control systems as part of his dissertation in U.C Irvine.  In academic terms, a RESTful architecture must comply with the following set of constraints –
-       Client Server Architecture
o  Clear separation of concerns with a modular approach to building systems where one entity publishes web services and one consumes them
-       Uniform Interface
o   Support heterogeneity of clients by exposing a uniform interface to the services, there by allowing clients and services to evolve independently of each other. Every resource is universally identifiable.
-       Stateless
o   Requests and Responses are self-contained and self-describing. Servers are stateless, thereby allowing for quick recovery from failures such as loss of requests or responses
-       Cacheable
o   Support for response caching at the clients or intermediaries, thereby improving scalability and performance
-       Layered
o   Support for proxies, gateways and other intermediaries between the clients and servers, allowing for the intermediaries to process messages before forwarding them on. The self-describing and stateless nature of the system would allow intermediaries to process the messages.
In simpler terms, REST is a set of guidelines and principles on how web services can be published and consumed over the Internet.  The common misconception is that it is a protocol and a standard. REST is neither a protocol nor a standard. It is however, standards based, thereby facilitating interoperability.  While REST makes no assumptions on the underlying protocol, HTTP is almost used universally as the underlying protocol for REST communications. Likewise, while there is no requirement on the data representation format, JSON is very popular as the data exchange format.
A lot of the popular services including Facebook, Twitter, Stripe, GitHub, Paypal and others today support a “REST” based API for developers to consume . With a lot of buzz around REST, everyone wants to to have a REST complaint API. However, a closer examination of these APIs would reveal that not all of them are truely RESTful.  Of course, it may not be always practical to model your resources and consequently, design an API that a RESTifarian would approve. Without a standard dictating what is allowed or disallowed, there is room for interpretation and consequently, there are variations in how these APIs are designed.
I recently gave a talk on REST API design at Self.Conference with the goal of describing the underlying principles that govern the design of RESTful APIs and the common anti-patterns to avoid. It discusses the approach to API Driven Development and  in fact, much of the content in the slides can serve as recommendations for API design in general .

The slides can be downloaded from here

(Me talking REST at Self.Conference)

No comments

In iOS8 Apple introduced the Modern WebKit framework. The Modern WebKit supports a multi-process architecture wherein web content is loaded in a process separate from the app (upto a limit). The framework is unified across the iOS and OS X platforms and includes a lot of performance enhancements such as the optimized JS Nitro Engine , hardware accelerated 60fps scrolling etc. It also includes support for WebGL for 3D rendering.

The WKWebView For Displaying Web Content

The WKWebView is a replacement for the UIWebView on iOS for loading web content within a native app. It is essentially a wrapper around the WebKit.framework and exposes an interface that is a lot more powerful than what the UIWebViews allowed.
One of the significant improvements is the simplified communication model between Native and JS .
This article will discuss how Native-WebView bridging can be achieved.
WKWebViews are associated with a WKWebViewConfiguration object. Multiple webviews can share the configuration object.
The following code snippet creates an instance of WKWebView

 self.webView= [[WKWebViewalloc]initWithFrame:self.view.frameconfiguration:self.webConfig];   


webView = WKWebView(frame: self.view.frame, configuration: webConfig)

Native to JS Bridging Using User Scripts.

User Scripts are JS that you inject into your web page at either the start of the document load or after the document is done loading. User scripts are extremely powerful because they allow client-side customization of web page, allow injection of event listeners and can even be used to inject scripts that can in turn call back into the Native app.
The following code snippet creates a user script that is injected at end of document load. The user script is added to the WKUserContentController instance that is a property on the WKWebViewConfiguration object.


// Create WKWebViewConfiguration instance
_webConfig = [[WKWebViewConfigurationalloc]init];

// Setup WKUserContentController instance for injecting user script
WKUserContentController* userController = [[WKUserContentControlleralloc]init];

// Get script that's to be injected into the document
NSString* js = [self buttonClickEventTriggeredScriptToAddToDocument];

// Specify when and where and what user script needs to be injected into the web document
WKUserScript* userScript = [[WKUserScriptalloc]initWithSource:js

// Add the user script to the WKUserContentController instance
[userController addUserScript:userScript];

// Configure the WKWebViewConfiguration instance with the WKUserContentController
_webConfig.userContentController= userController;


  // Create WKWebViewConfiguration instance
  var webCfg:WKWebViewConfiguration= WKWebViewConfiguration()

  // Setup WKUserContentController instance for injecting user script
  var userController:WKUserContentController= WKUserContentController()

  // Get script that's to be injected into the document
  let js:String= buttonClickEventTriggeredScriptToAddToDocument()

  // Specify when and where and what user script needs to be injected into the web document
  var userScript:WKUserScript =  WKUserScript(source: js,
                                         injectionTime: WKUserScriptInjectionTime.AtDocumentEnd
                                         forMainFrameOnly: false)

  // Add the user script to the WKUserContentController instance

  // Configure the WKWebViewConfiguration instance with the WKUserContentController
  webCfg.userContentController= userController;

JS to Native Bridging Using Script Messages

Your web page can post messages to your native app via the
window.webkit.messageHandlers.<name>.postMessage (<message body>) method.
Here,  “name” is the name of the message being posted back. The JS can post back any JS object as message body and the JS object would be automatically mapped to corresponding ObjC / Swift native object.
The following JS code snippet posts back a message when a button click event occurs on a button with Id “ClickMeButton”

varbutton = document.getElementById("clickMeButton");
button.addEventListener("click", function() {
            varmessageToPost = {'ButtonId':'clickMeButton'};

Handling Callbacks Using Script Message Handlers

In order to receive messages posted by your web page, your native app needs to implement the WKScriptMessageHandler protocol.
The protocol defines a single required method. The WKScriptMessage instance returned in the callback can be queried for details on the message being posted back.
ObjC :

- (void)userContentController:(WKUserContentController*)userContentController
                               didReceiveScriptMessage:(WKScriptMessage*)message {
    if([message.name isEqualToString:@"buttonClicked"]) {
        // The message.body contains the object being posted back



func userContentController(userContentController: WKUserContentController,
                           didReceiveScriptMessage message: WKScriptMessage) {

        if let messageBody:NSDictionary= message.body as? NSDictionary{
            // Do stuff with messageBody


Finally, the native class that implements WKScriptMessageHandler protocol needs to register itself as a message handler with the WKWebView as follows.


// Add a script message handler for receiving  "buttonClicked" event notifications posted
from the JS document
[userController addScriptMessageHandler:selfname:@"buttonClicked"];


// Add a script message handler for receiving  "buttonClicked" event notifications posted
// from the JS document
userController.addScriptMessageHandler(self, name: "buttonClicked")

Sample Code:

A complete example app demonstrating the bridging concept can be downloaded from https://github.com/rajagp/iOS-WKWebViewBridgeExample-ObjC.git. The Swift Version can be downloaded from https://github.com/rajagp/iOS-WKWebViewBridgeExample-Swift.git.
In this sample app, we load a simple HTML page that has a button using a WKWebView. When the page loads, the native app injects a JS ("User Script") into the loaded document that listens for button click event and calls back into the native app ("Script Message") . The native app implements a listener to handle the callback message from the web page and updates the color of the button from within the callback handler
I did a short presentation on this topic at CocoaHeads. The presentation can be downloaded from here.

No comments

If you are developing an iOS app that communicates with a server over the network, the Network Link Conditioner is an invaluable tool. You can use the tool to “condition” the network communication to simulate various network conditions. ProTip: You never ship an app which requires network communications without putting it through the wringer with the Network Link Conditioner tool. Details on the Network Link Conditioner available here.

Often times, you need to develop against a server running on localhost while running your app on a simulator. This may be because you don’t have access to the remote server or you don’t have network connection for instance. 
So how do you simulate different network conditions when testing against localhost server?  Or what if you wanted to selectively throttle traffic ? A network Link Conditioner cannot be used to condition local loopback connections and it impacts all traffic flowing through the network interface.

So here is a really awesome preference pane called SpeedLimit which can be used to condition loopback connections and selectively throttle network traffic based on ports.

  • You can download and install it from here

           You may have to tweak your Mac's Security & Privacy preferences so as to allow the download.

  • Once installed, you can launch  SpeedLimit  from System Preferences.

         Set the host as “localhost” , set the port, select the speed and select “Slow Down” to slow down the network. Sometimes, you may have to set up the host as the local loopback address “”

The revert back , press “Speed Up” button


No comments

I had an awesome time presenting on Mobile Development at Girl Develop It, Ann Arbor group. There was an incredible level of interest in this topic that explained the good turnout despite the stormy weather. 

The talk covered the basics of developing native apps for the iOS, Android and Windows platforms. In addition, an overview of some of the major cross-platform tools and frameworks including Appcelerator Titanium, Cordova PhoneGap and Xamarin Mono were provided. The talk also briefly addressed the concept of Responsive Web Design as it applies to mobile website and web apps.

You can download a copy of the talk from here and video of presentation is available on YouTube

Now a brief note on the evening itself : The topic of "Women in Technology" (or lack thereof) has always been an important to me and I am always looking for opportunities to help bridge the gender gap.

So it was encouraging to be speaking to an audience where women techies were in the majority (and a special shoutout to all the men who made it and showed their support to the group). Judging by the enthusiasm of the attendees, it is quite clear that women are just as curious and interested in technology as their male counterparts  I believe that a forum that allows women to learn without fear of being judged and network comfortably with fellow women techies can be vital in encouraging more women to join the rest of us. 

No comments

I recently gave a talk on Dynamic Fonts at Cocoaheads meeting. You can download the presentation and sample code from here.

iOS7 introduced a cool feature called Dynamic Fonts. What it essentially allows you to do is to set your preferred reading text size in Settings (General or Accessibility) app of your phone and voilà, all apps that support dynamic type automatically adjust to display text content according to the preferred size setting

In this post, I’ll go over what you would need to do to support dynamic type within your apps so that yours will be one of the cool apps that reacts to the preferred text size change!

UITextKit, Text Styles and Font Descriptors

iOS7 introduced UITextKit – a powerful framework that allows you to support rich text content, layouts and without the complexities of drawing it with Core Text or having to use UIWebView.
An important component of UITextKit is TextStyles. Text Styles describe an intended use of a font .

The table below shows the list of supported text styles and the font descriptors that define them for the case when we set the preferred text size slider settings to the center.

Text Styles
Font Descriptor
  NSCTFontUIUsageAttribute = UICTFontTextStyleHeadline;
NSFontNameAttribute = ".AppleSystemUIHeadline";
NSFontSizeAttribute = 17
UIFontTextStyleSubheadline || Read more


Functional Testing is system level , end-to-end testing of your app from a user's perspective. Automating the process of functional testing of your app offers several benefits – it saves time and effort, it's repeatable, simplifies regression testing, enables testing with large data sets and it can be tied into your Continuous Integration process. UI Automations is an automated functional test framework from Apple. Here, user interactions are driven by test scripts are written in JavaScript and executed using the Instruments Automation tool.

While there are several other automated functional test tools available including Calabash, KIF, Frank and Fone Monkey, UI Automations has the benefit that it is very simple to use, needs minimal or no changes to your existing app and since it's from Apple, it is (fairly) well supported and maintained.

I recently gave a talk on automated functional testing of iOS apps using UI Automations. You can download the presentation from this link. There is also a sample demo application with a corresponding set of UI Automation test scripts.


Today, I gave an introductory level technical talk about developing mobile apps for iOS platform at the American Society Of Engineers Of Indian Origin (ASEI), MI. The ASEI is "a two level (National and Local) non-profit organization of engineers and technical professionals of Indian origin". You can learn about them at http://www.aseimi.org. I was aware of the group but I had never attended any of their meetings, so  I was not sure what to expect.

Right after work, I made the 45 mile drive to the ASEI meeting. Fighting the evening rush hour traffic, I reached there on the nick of time ; I probably made the organizers quite nervous!

There was a pretty good turn out. These were people, who just like me, had driven in from work and who probably had ten other places they'd rather be on a fall evening with picture perfect weather. I had to ensure that my talk was well worth their evening.

Soon after the featured mobile app presentation, I got started. I surveyed the room and learnt that there were less than five developers in the room. The rest of the audience was a mix of people with diverse backgrounds (different industries , different roles, varying demographics, a few were not even iPhone users). 

My presentation was intended to be fairly technical , so my challenge was to make it appeal to the diverse audience. Although they were all not developers, I knew they all had one thing in common – they were very keen on learning more about iOS mobile development. I knew that was a start.

So for the next hour or so, I quickly moved through my slides. I had material for couple of hours but I tried to focus on material that would broadly appeal.  Then the questions started pouring in and they were all very relevant. People were paying attention (well- at least most of them were) and it was interesting to see different perspectives. 

I left the meeting with a greater sense of community. 

You can download my presentation from here. It is intended to be a primer to the iOS platform and developing apps for it .

No comments

This post describes a way to scale the text content that is presented within a UIWebview of your iOS app. Often times, there is a need to zoom in or zoom out the text content presented within UIWebview container in response to user actions. 
•   Run a simple Javascript on the contents of the webview using the stringByEvaluatingJavaScriptFromString method in order to adjust the size of the text.


NSString *jsForTextSize = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.
webkitTextSizeAdjust= '%d%%'", updatedFontSize*100/DEFAULTWEBVIEWFONTSIZE];
[self.myWebView stringByEvaluatingJavaScriptFromString:jsForTextSize];

In the JS above, DEFAULTWEBVIEWFONTSIZE refers to the default font size of the text content presented within the web view and updatedFontSize refers to the desired font size. So for example, if DEFAULTWEBVIEWFONTSIZE is 18 and updatedFontSize is 9, then updatedFontSize*100/DEFAULTWEBVIEWFONTSIZE evaluates to 50.


•   Next step is to adjust the frame height of the web view so the scaled text content is visible. The simplest way to do this is to have the UIWebView as a subview of a scrollable view (UIScrollView or  its subclass ).  That way, you can adjust the web view frame height  and correspondingly, the content size of the scroll view that encompasses it. Adjusting the  web view height is a bit tricky as described below.


The sizeThatFits method on web view returns a size that best fits the content. The problem with this is that when you scale up, the method returns the updated size but if the web view is large enough to display the specified content, then scaling down will not update the frame size but instead, the current frame size is returned.


So first , reset the current frame height  of the web view to a small value like 1.

    CGRectadjustedFrame = self.myWebView.frame;
    adjustedFrame.size.height= 1;
    self.myWebView.frame= adjustedFrame;

Now, obtain the frame size that would best fit the content. Since the current frame size is 1, we are scaling up. Update the frame size of the web view with the new frame size.

   CGSizeframeSize = [self.myWebViewsizeThatFits:CGSizeZero];
    adjustedFrame.size.height= frameSize.height;
    self.myWebView.frame= adjustedFrame;

Finally, update the content size of the UIScrollView containing the web view to accommodate the scaled content.

    CGSizescrollViewSize = self.myScrollView.contentSize;
    scrollViewSize.height= adjustedFrame.size.height+ self.myWebView.frame.origin.y;
    self.myScrollView.contentSize= scrollViewSize;

You can download a sample project that scales the text content of web view from  here. Shown below are some screenshots of the app.




No comments

As an iOS developer (or any developer for that matter), it is not uncommon (or dare I say- its “very common”) for us to defer things while coding so as to not disrupt the current coding flow. For instance, handling of a special case or updating an algorithm with a more efficient one or just a reminder to double check a certain logic . To remind ourselves, we typically include a comment like “ToDo: Handle error code -1020” in our code.


Now, before we realize it, we have several “ToDos” and “FixMe” scattered throughout our project and unfortunately, many of them go unattended . Note that “attending” to them may be as simple as removing the comment because we have in fact handled the “To Do” but have just forgotten to remove the now obsolete comment which leads to clutter and confusing code.


So here is a neat little perl script that I found (and tweaked a wee bit for my purpose) that solves the problem. The script is executed  every time my project is built. The purpose of script is simple. The script greps for keywords in all the .h and .m files in the  ${SRCROOT} folder and prefixes it with a “warning”  label.

KEYWORDS="TODO|ToDo|TODO:|FIXME:|\?\?\?:|\!\!\!:" find "${SRCROOT}" \( -name "*.h" -or -name
 "*.m" \) -print0 | xargs -0 egrep --with-filename --line-number --only-matching "($KEYWORDS).
*\$" | perl -p -e "s/($KEYWORDS)/ warning: \$1/"


Now, every time, I compile my project, the script runs and displays all statements that begin with keywords listed in the KEYWORDS reg expression show up as warnings. They are now hard to miss and I can ensure that all the “To Do”s are handled in a timely manner.

To add the script, select “Add Build Phase” under the “Build Phases” tab of Xcode project settings.


Then , cut and paste the script to the “Run Script” section

Now, when you build your app, you should see all comments that include the keywords mentioned in the script listed as warnings.

No comments

The Problem…

If you have been using Xcode  (the latest version as of writing this post is Xcode 4.6.2 ) for an extended period of time, testing your app on the iOS simulator, you may eventually encounter a “Resource temporarily Unavailable” build error . There are no build errors associated with your source code but the system is unable to successfully build your app and launch the simulator to run it . You would observe something like this in your build output.



So what’s going on?

The reason this occurs is because every time you launch the iOS simulator through Xcode to run your app and then quit /stop running the app, Xcode leaves behind a Zombie process.  If you are not familiar with Zombie processes in Unix, essentially, it is a process that has completed execution but whose entry remains in the process table. It is the responsibility of the parent process to eventually clear these processes. The zombies don’t use any of the computer resources so you won’t observe a depletion of resources , but the problem is that in this “undead” state, they hold on the PID or Process Identifier. The implication of this is that eventually, your system will run out of PIDs to assign to new processes, thereby resulting in a failure to spawn or launch a new process.

You can confirm this behavior by running your iOS app through Xcode a few times and then running the “ps” command on the terminal window. You will observe a bunch of zombie processes listed for your app. The “Z” in the “S” (or “STAT” ) column indicates that “symbolic state” of the process is a “Zombie“.

Priya-Mac-01:$ ps -aelf



 501 928 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Fri11AM

 501 1072 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Fri11AM

 501 9473 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Fri05PM

 501 11380 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon09AM

 501 11599 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon09AM

 501 11614 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 11758 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 12412 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 12564 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 13245 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 13407 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon11AM

 501 13590 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 13725 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) 19Jun13

 501 14545 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon12PM

 501 14646 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon12PM

 501 14761 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon12PM

 501 14835 233 6000 0 0 0 0 0 - Z 0 ?? 0:00.00 (MyApp) Mon12PM


Priya-Mac-01:$ ps -aelf | grep "MyApp"|wc -l


In my case, there were 272 zombie processes associated with my app that Xcode didn’t reclaim. So in case of the Xcode, you will eventually notice that you are no longer able to build the app and launch the simulator to run it. In fact, you probably won’t be able to launch  any new application. Yep- not a good place to be.

So what are your options?


The simplest and safest method is to reboot your system. This will get rid of the zombie processes

Re-initializing/Killing the Parent Process:

Generally , killing the  parent process corresponding to the Zombie processes should take care of it but unfortunately, in the case of Xcode, the parent process is the system launchd process. The launchd is a core system process that handles the launching of many of the other processes.  Issuing a “kill” command to the launchd process can result in undesirable results and can even make your system unresponsive. So DO NOT kill the launchd process. You could try to re-initialize the process using the kill with HUP (“Hang Up”) option but you are probably better off rebooting your Mac.

If you are curious, you can follow the steps below to determine the parent process of the Zombie Xcode process

1) You can identify the PID  (“ppid”) of the parent process corresponding to the zombie process using the command

Priya-Mac-01:$ps -p <PID of MyApp Zombie Process> -O ppid

This will output the ppid of the parent process corresponding to the Zombie process,

2) You can get details of the parent process using the following command

Priya-Mac-01:ps -p <PID of Parent Process>

PID TTY           TIME CMD

  236 ??         0:00.75 /sbin/launchd

The output of the above command indicates that the launchd process is parent process.

You can find more details on Zombie processes at you can check out  the details in http://en.wikipedia.org/wiki/Zombie_process.