All posts by Abhijit Joshi

iOS – A simple introduction to Swift

I don’t know who once said these words, but they apply without question to this blog post.

Make everything as simple as possible – but not simpler.

Anyways, if you have nothing better to do with your day, you might as well learn how to program using Apple’s shiny new language called Swift. Granted it is not so shiny because it has been a while since it was born. But it is still somewhat of a toddler and lots of fun to play with – although this toddler is a lot smarter than what you might think.

Ok – so this post is not about to teach you how to program – or about how to write apps for iOS. It is more of a visual inspiration to start coding in Swift for those still reluctant to make the leap from good old Objective-C. Yes, I am one of those who fell in love with and still love Objective-C. I was particularly shocked when I just found out what Swift is going to do to the increment operator ( i ++ ). But you can read about that elsewhere if you don’t already know.

Enough chit chat – let’s get to the point. Here we go:

Screen Shot 2016-06-20 at 11.00.58 PM

The project here has a single button and a label. The label begins life with the number 1. Pressing the button doubles the value of the label and this keeps happening forever. I have not checked what happens if you keep doing this for a long time. Your finger may not like it much.

1…2…4…8…16…32…you get the idea.

Granted, this is a really simple app – but hey, we got to start somewhere and this is as good a place as any.

Happy Coding!

iOS – Using MKLocalSearchCompleter for Map Search

Google has always been somewhat ahead of the game in map search – for example in suggesting “search completion” strings when we start typing in places, points of interests or partial addresses in Maps. But Apple is catching up – and catching up fast.

In iOS 9.3, Apple introduced a very useful class for developers called MKLocalSearchCompleter – one that is sure to swing several iOS dev teams to lean towards using Apple Maps in lieu of Google Maps for implementing the search completion functionality in their apps.

The basic idea of search completion is to be able to type in a partial string in a search box and get several suggestions in real time as we are typing in. The user can then tap on one of the suggested options – and be taken to that location on the map view.

Here is an example of what is now possible using the MKLocalSearchCompleter class :

Screen Shot 2016-04-03 at 10.37.24 AM

To implement this functionality in your apps, just follow these simple steps:

1.

Add the delegate to your interface.

2.

Add a couple of new properties:

3.

Initialize the class somewhere in your implementation:

4.

Add these delegate methods and use the results returned in your app:

In the above code, I am printing out the results returned in the array – we can use these to update a table below the search box in real time.

I was quite impressed with how responsive and relevant this search functionality is in a real app. For additional details, check out the official Apple Docs.

Nice work, Apple!

iOS – Unit Testing

xcode2

This post will talk briefly about setting up a bare-bones iOS app to illustrate what unit testing is all about and how to utilize the XCTest Framework for writing your own tests.

Imagine that you are writing a method to validate US and Canadian ZIP codes (or postal codes, as they’re called in Canada). In the US, ZIP codes are 5-digits long. Things like 77335, 06226, 29631 and so on.

In Canada, postal codes are typically written using 6 characters, with a space after the first three characters, like so:

LNL NLN

In the above code, L is a letter from the alphabet and N is a number or digit from 0-9. So Canadian postal codes can look like A2K 4L8, K7G 5T9, M2N 6P8 and so on. To make things more interesting, there are some additional rules about what letters are allowed (or rather not allowed) at various positions:

  • The first letter cannot be W or Z.
  • The letters D F I O Q U are not allowed at any location.

There might be more rules, but we’ll stop here. You get the idea where this is going. We’ll need to write a method that receives a user input string and then parses the string to make sure all these rules are met (for both US and Canada). Let’s assume you cook up the following class method somewhere in your model:

If the user enters the correct ZIP code, this method should return YES, otherwise it should return NO.

Once you finish developing this method, you simply go to the test section of your project and start adding in various test cases to check your method. There are some who maintain that these test cases should be written even before you create the above method – we will not argue about what approach is best – do whatever works for you.

For simplicity, this post only talks about the following testing methods, which suffice for our purpose here:

  • XCTAssertTrue( something_that_should_be_true, @”optional message displayed when that something is false” )
  • XCTAssertFalse (something_that_should_be_false, @”optional message displayed when that something is true” )

This is how you use them in the code (all you need is to include the header file of your model class in the test case file):

You can add as many tests you like in this file. To run these tests, use

Product —> Test (or the keyboard shortcut  Command + U)

Xcode will run all your tests and place cute little check signs next to each test to let you know which tests pass and which tests fail.

That’s it! Isn’t unit testing cool? Now that I’ve wrapped my head around the basics, I will start adding unit tests to several of my iOS projects.

Hunt for the climate crisis toy

Trains of thoughts are triggered by strange things. Our memory is amazing but fragile so I’m going to record some thoughts in cyberspace. It’s always wise to wait a few days before recording thoughts – so only the important bits remain and one can wait and see if there are any other connections and memories that are linked to what we were thinking of at that time.

Here is the “train of thought trigger”, last seen on an American Airlines flight from DFW to ATL. I took a photo of it so I could use it later for this blog.

Screen Shot 2014-12-24 at 11.59.31 PM
The most important thought I had after staring at this image for a long time is that I need to look for a globe (preferably located in the real world) that will have the ability to change the sea level. How would the world look like if the oceans rise by 10 feet? Would our home become a beach-front property?

What would earth look like if all the oceans were drained completely? Anyone for a hike down the Mariana trench? So I want a globe whose surface is 3D relief – you know what I mean. That would be one cool toy! I know it is a bit late to be asking this but Santa, you listening up there? I’ve mostly been good this year.

Santa to his elves: Hey, have we got anything like that, guys?

Elves: Nope. Is this guy crazy or what?

So guess I’m not getting it from you-know-whom. Too bad.  The next option is to search for it, or “google it” as it is called these days. Actually, I imagine the preferred practice is to first google it and then resort to Santa – but that is neither here nor there. Just to be totally clear, I googled the phrase “3d globe with sea level changer”. There were quite a few hits. But I’m not really interested in computer simulations of this by NASA or Rutgers University. I changed my search phrase to “toy 3d globe with sea level changer” and then hit the jackpot. Almost. There is an app sold on Amazon called “Elevation Earth” – which seems to simulate this exact experience. A few clicks later I found the iOS version – who really cares about Amazon or Android apps anyway?

Screen Shot 2014-12-25 at 12.48.45 AM I looked carefully to check if my better half was around and then clicked on “Buy”. The app is good and easy to use. Here are some snapshots of how the world looks like when sea-levels rise by +476m. The Appalachian mountains now become islands on the former US east coast. Most of Europe is underwater except the mountain ranges of course. If you have a swiss-bank account, your money is safe. Further to the east, the mighty Himalayas are now facing the ocean as most of India is overwhelmed.

Screen Shot 2014-12-25 at 1.08.58 AM
For now, I am content to play with this app – but if anyone out there knows of a real 3D globe that can simulate stuff like this, I would love to get in touch with you.

Book Review: 1Q84 by Haruki Murakami

Screen Shot 2014-12-04 at 11.30.11 PM

If you’ve read Orwell’s 1984, you should be aware that this story has nothing to do with a dystopian future where Big Brother is watching your every move. It is, in fact, a tale where the lead characters wander off into an alternate timeline or parallel universe. Not everybody seems to notice that the world around them has inexplicably changed in subtle and then increasingly perplexing ways.

The book begins with what might be the best opening chapter I’ve read in a long time. A young woman is stuck in rush-hour traffic in a taxi. She is traveling on a highway in Japan and the music playing inside the taxi is Janacek’s Sinfonietta. This, by the way, is a beautifully crafted piece of music. I would probably have never heard of it if not for this book. This music alone is worth the price of admission.

We learn later that the woman’s name is Aomame. She has an important appointment and is getting late because of the traffic jam. The taxi driver suggests that if it is really that important, she could get out of the taxi and climb down an emergency stairway that will take her to the city streets below. Once there, she could catch a train to go to her destination. However, he also warns her that the world might change in subtle ways if she chooses to do this. His parting words to her are that there is only one reality and she would do well to remember this.

She does climb down the emergency stairway and the world does begin to change. But only for her, it seems. Have you ever wondered what you might feel like if you saw two moons in the sky and realized that everyone else is probably seeing only one moon? This is one of the many changes Aomame must learn to live with.

The second primary character in the book is a young man called Tengo. He is an aspiring writer who is hired by an editor to help ghost-write a fictional book by a beautiful but dyslexic girl. The book goes on to becomes a best-seller and wins a prestigious literary prize but Tengo is troubled by the story the girl has written and is not completely happy that he played a secret role in getting the story to a wider audience. Tengo’s world also begins to wander off in the strange reality that Aomame is experiencing.

The book alternates between Aomame and Tengo until we realize that they are on a collision course. Apart from these two lead characters, there are several memorable characters including an old, soft-spoken dowager who hides a terrible secret, a gay bodyguard who thinks of himself as the ultimate professional in his field and of course, the mysterious teenage girl who wrote the original story that Tengo later modified and polished. All characters are beautifully developed and you actually will care about what happens to each of them as they play out their parts. Add to this a weird religious cult called “Sakigake” and last but not least, the so-called “little people” who seem to be pulling all the strings.

The entire story takes place in what you and me would refer to as the year 1984. The title 1Q84 refers to the alternate universe in which Aomame thinks she has been drawn into. Within the book, there is a fantastic, somewhat creepy and almost dream-like tale about a town full of cats. I have never been able to visit this town in my dreams. But if I do wander there on some night, I hope I return in one piece to the world of the waking.

Long story short, go get this book and read it through to the end. You will not be disappointed. Or even better, get the audio CD version and listen to it. The one common thing about all great stories is that they stay inside your mind forever. I will remember this story for a long time to come. And so will you.

iOS – Mandelbrot

INTRODUCTION

Is it possible to fall in love with a mathematical object? If the object in question is the Mandelbrot set, then the answer is a definite yes. This post talks about an iPad app that helps us explore the strange, hypnotic and never-ending beauty of this well-known fractal.

Screen Shot 2014-05-29 at 12.30.42 AM

The image above shows a zoomed-in view of a certain part of the Mandelbrot set. The points in black are inside the set and those in blue are outside the set. Much of the artistic appeal of the set depends on the color scheme you design to mark the points at the borderline. I used the exact same color scheme from my C++/OpenGL tutorial and a lot of code (in the Model) was directly ported from C++ to Objective-C.

The displayed image is divided into 4 quadrants by the white lines. You select where you want to zoom in by tapping the appropriate block with your finger. For example, here is a sequence of touch events from the very beginning of the set:

Screen Shot 2014-05-28 at 10.28.47 PM

Naming the blocks using 1 (top-left), 2 (top-right), 3 (bottom-left) and 4 (bottom-right), the journey above may be abbreviated thus: 1-4-3-1. The large image at the beginning of this article was obtained using the following sequence: 1-4-4-1-3-3. The possible journeys are infinite and one can probably spend several lifetimes exploring every nook and cranny.

UNDER THE HOOD

The overall design of this app follows the usual Model-View-Controller strategy. The model consists of the minimum and maximum (x, y) coordinates of the window in the complex plane, the number of divisions along x and y (resolution), a 2D array that holds the parameter value used to color the set and a method to determine whether a point belongs in the set or not. Here is the implementation of the Model class:

There are two views, both subclasses of UIView: one displays the set itself and the other draws the horizontal and vertical centerlines. The implementation of the Class that draws the set is provided below for reference:

Note that we are using the Core Graphics API to render the 2D color data. This is not necessarily the best approach, but I believe it is the simplest to understand and implement. In the future, I plan to use OpenGL-ES and accelerate the calculation and graphics using GPU computing (CUDA/OpenCL).

Finally, the controller interprets the model for the views and updates the model data based on user touch-events. Essentially, we figure out which quadrant the user touched and update the minimum and maximum x and y coordinates appropriately, ask the Model to re-calculate the 2D array in the new window and send the updated data to the View for rendering. Here is the Controller implementation:

Notice we have a RESET button to go back to the original window. This merely resets the minimum and maximum x and y limits to their original values.

The entire source code can be cloned from

https://github.com/jabhiji/ios-mandelbrot.git

Happy Xcoding!

iOS – Maze

My latest app for the iPhone is about creating a maze pattern using the touchscreen and then guiding a ball through the maze by tilting the phone in the appropriate direction. You create the maze in a block-by-block fashion by tapping the screen with your finger. One tap puts a solid block. Another tap at the same location removes the solid block. You can create any maze pattern, for example the one shown below.

Screen Shot 2014-05-23 at 11.28.46 PM

Hitting the CLEAR button removes all solid blocks. The ball bounces off the edges of the domain and also bounces off solid blocks. Implementing the model logic where the ball bounces off the domain edges is quite straightforward. Extending the model to include the solid blocks required some additional thought and this was perhaps the main take away from this project for me.

The entire source code can be downloaded from:

https://github.com/jabhiji/ios-maze.git

The Model class contains all the necessary properties and methods to specify the structure of the maze and to specify the ball location and update the ball location with time. The maze is simply a 2D integer array (LGEO), where the array element is 1 if the location is a solid block and 0 otherwise. Here is the Model class interface:

The name “LGEO” stands for “Logical GEOmetry array” and is a terminology rollover from some of my old CFD research codes, where a similar 3D array is used to describe a porous material. The number of array elements along X and Y is nx and ny respectively and the size of the LGEO array is thus nx*ny. The width and height are obtained based on the size of the UIView and used to calculate the grid size along X and Y. The remaining parameters specify the ball size, location, velocity and acceleration. The implementation file shows the details about how the model handles collisions:

The basic idea of the ball-maze collision logic is this: At each time instant, we find out the location of the ball within the 2D (LGEO) array and find out the status (1 or 0) of all 8 neighboring cells. If the ball hits a neighboring solid block, we reverse the appropriate velocity component depending upon the location of the impact. The picture below shows a schematic of the idea, where I show balls impacting a solid square block from various directions.

Screen Shot 2014-05-24 at 5.46.30 AM

For the balls on the left and right of the block, the x-component of the ball center (relative to the square center) is more than the y-component. In such a case, we reverse the x-component of the velocity. For the balls to the top and bottom, we reverse the y-component of the velocity.

The values in the LGEO array can be changed in real-time by the user. These touch-based events are handled within the Controller. The method used to implement this logic is copied below for reference.

Notice that we have a bounds check to make sure we don’t specify memory locations outside the specified array limits. Each touch in the UIView window toggles the LGEO array value at that location.

A side note: For those of us coming from C/C++, it may seem a little strange to not have to constantly clean up after our array declarations on the heap. Objective-C implements this clean up automagically via automatic reference counting.

Now that you understand the basic idea of how to specify a maze and implement collision detection, it is just a matter of detail to extend this project to create a game with various difficulty levels and keep track of the score and things of that sort. Perhaps I will return some day to make a game of this sort.

Bis dahin, Happy Xcoding!

iOS – Embedding Web Pages

This short post is a tutorial on how to embed a specified webpage on the screen using the UIWebView class. This class includes several methods to load web content and several properties to control how the web page is displayed inside the window.

The screenshot shows a simple example where I embed the exact same web page (http://www.joshiscorner.com) in two different UIWebView objects:

Screen Shot 2014-05-19 at 11.43.17 AM

STEP 1: Set up the storyboard

Drag two UIWebView objects to the storyboard and size both views to be 280 by 250.

STEP 2: Make connections

Make IBOutlet connections by ctrl-clicking from the UIWebViews on the storyboard to the ViewController interface.

STEP 3: Specify the URL and display it inside the window

The ViewController implementation is copied below.

As usual, we synthesize the two UIWebView properties and then use the NSURL class to specify the URL we wish to load. In this case, we load the same URL in both the windows. But in the top window, we load the page “as is”, that is using the width specified in the HTML/CSS on the remote server. In this case, the width of the page is set to 970px, while the width of the iPhone screen is 320px. So when we display the page “as is”, only a fraction of the content is seen inside the window.

In the second view, we use the “scalesPageToFit” property of the UIWebView object and set it to YES. This forces the view to display the entire width of the web page.

You can learn more about the UIWebView class on the Apple Developer website.

iOS – Paintbrush App for the iPhone

How do I draw free-form shapes on the iPhone screen with my finger? This post is an introduction to a simple paintbrush style app that does exactly that. Actually, this type of app is much more suitable for an iPad, but we’ll stick to the iPhone for now.

Screen Shot 2014-05-15 at 5.04.44 PM

In the above app, you simply place your finger inside the black UIView window and start drawing whatever you want. The default drawing color is white. To change to a different color, just click on the appropriate color buttons. To keep things simple, there are only 5 color options.

How it works under the hood

The heart of this app is a set of pre-built methods that can sense touch events and return the coordinates (relative to the view) where your finger touches and interacts with the screen. There are three primary touch events:

  • Your finger touches the screen for the first time (touch begins)
  • Your finger moves from point A to point B on the screen
  • Your finger leaves the screen (touch ends)

This is how these methods appear in actual code:

The methods are inserted in the View Controller implementation, and the usual practice is to override the default implementations (which do nothing) with our own custom implementation.

Like the other apps we developed so far, the ViewController interface contains IBOutlets, IBAction items from the storyboard and other properties used in the implementation. Here is the ViewController interface for this app:

The implementation file contains the meat of the app and I encourage you to uncomment some of the NSLog calls to get a feel of the numbers (x and y coordinates) returned by the three touch methods.

Once the finger coordinates (x, y) are obtained using these methods, we allocate a Circle object (subclass of UIView) that draws a filled circle of a certain size at that (x, y) location. As your finger moves, the coordinates keep changing and we scramble more and more Circle objects to draw additional circles along the path. If you move your finger too quickly, you will actually see the individual circles. Go slow if you want to create the illusion of drawing a continuous thick line.

Notice that we use a NSMutableArray to keep track of all the Circle objects because later on, we want to clear the entire screen by removing all those views from the superview. The NSMutableArray is initialized with a maximum capacity to hold 1000 objects. Obviously, as we draw more and more circles, the size of the NSMutableArray and the memory needed by the app increases. Because of this reason, you will notice some sluggishness in the drawing when you draw far too many shapes in the view. All this memory is released when we hit the CLEAR button (triggering the clearScreen method above).

Finally, here is the interface and implementation file for the Circle class:

Clicking the color buttons in the UI triggers methods that change the circleColor property. Background images of the appropriate color were used for all the color buttons.

If you wish to reduce the thickness of the lines in your drawing, simply reduce the frame size when you draw the Circle object. The size I am presently using is 20 points (circle radius = 10).

In summary, this post was a quick introduction to the world of sensing touch events in iOS and using this information to create a simple paintbrush-style app. Want some suggestions for using this app? How about teaching toddlers how to draw numbers and letters in English or in your native alphabet?

As always, you can download the entire source code for this project from my GitHub link:

https://github.com/jabhiji/ios-touch-paintbrush.git

Happy Xcoding!

iOS – Return to HOLES

In a previous post, I talked about my first iOS game using PhoneGap, which I called HOLES. At that time, I did not know as much about Xcode and Objective-C as I do now. Because of this reason, I wrote that game using HTML5/JavaScript and used PhoneGap to port the game to iOS.

Now that Objective-C is becoming more and more easy to use, I decided to revisit the game and write a completely native version. Here are some screenshots from version 1.0:

Screen Shot 2014-05-13 at 7.24.02 AM

I admit that it took me a lot more time to write this native iOS version compared to the HTML5 version, primarily because I am relatively new to Objective-C and to object oriented programming (OOP) in general. But it was well worth the effort because I learned several new things while working on this project and I believe the end result is an app that is more polished compared to the HTML5 version.

The entire project can be downloaded from my GitHub page using the following link:

https://github.com/jabhiji/ios-holes.git

What follows is a brief summary of the design – and some nuggets from Objective-C  – that I hope will be helpful to the new game developer.

The Model

Think about what parameters we might need in the abstract model of our game. To begin with, we are using the accelerometer to control the movement of a ball on screen. So we need to know the ball radius and the location (x, y) on screen. We also need the acceleration and velocity components and need some logic to (1) update the ball position (2) check for collisions with the domain walls (3) rotate the hole pattern (4) check if the ball falls inside a hole (5) check if the ball reaches the flag and (6) update the score and number of balls remaining and (7) detect when the game ends and reinitialize all parameters when the user presses the RESTART button.

All this and more is done using the GameModel class and the interface for this class is copied below.

As usual, the idea is to instantiate an object of this class in ViewController and use the above properties and methods to help the controller send the appropriate data to the view for displaying the ball and hole pattern on screen and figuring out how the scene changes with time.

This app makes heavy use of an Objective-C class called NSMutableArray, which is a convenient way to deal with an array of objects. The Apple Developer website sums this up perfectly:

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray.

In the GameModel class, we use NSMutableArray to create an array of x-coordinates, y-coordinates and radii of the black holes. This is how you allocate and initialize the array:

If you wish to access the data (floating-point numbers) stored in this array, you can use the following:

In this case, we are using simple floating point numbers as the “objects” stored in this array, but the same idea works for storing an array of objects of any class. This is what makes NSMutableArray a powerful and useful tool.

Like “addObject”, another useful method in NSMutableArray is “insertObject:(object) atIndex:(integer)”. We use this to reset the hole coordinates in one of the our GameModel class methods:

We use NSMutableArray again in the Controller to manage the task of displaying all 5 holes.

The View(s)

The main items we need to display on screen are: (1) the yellow ball (2) the flag and (3) the black holes. Because all these shapes are easy to construct from geometric primitives, I decided to use custom UIView-based drawings. I called these classes Ball, Flag and Holes and they all inherit from the same UIView class.

The yellow ball:

The black hole:

The flag:

In the ViewController, we can instantiate objects of class Ball, Holes and Flag and specify where we want to display them in the superview.

The Controller

Because we need the accelerometer, we must add the CoreMotion framework to our project and include the corresponding header file in our interface. Here is the complete controller interface, with connections to the main storyboard:

controller interface

In the implementation file (ViewController.m), we talk with the model and views to get the game going. The first step is to synthesize the properties we defined in the interface so Objective-C can provide us with the corresponding setter and getter methods for using these objects.

Some things you may want to pay close attention to in the above code are:

  • Making the background transparent for UIView objects.
  • Clipping things outside the view
  • Creating an array of 5 objects of class “Holes” using NSMutableArray and displaying these objects.
  • Starting the accelerometer and the NSTimer based game animation.

The rest of the ViewController code deals with the main game loop, where we update the model and draw the ball and holes at their updated locations and keep track of the score and how many balls we have left.

I used a simple UILabel for displaying the “GAME OVER” message when we no longer have any balls left. This label is hidden from view for most of the game with

When all balls are gone, we simply un-hide this label and bring it to the “front” using

If you’ve read this far, you now have a pretty good idea of the thought process and coding decisions that went into making this game work. I think I am enjoying Objective-C more and more with each new app I write.

Happy Gaming!