Getting around UI Testing Failure Error in Xcode

Recently, I started playing around with the UI Testing features in Xcode 7. To my surprise the recording feature was extremely useful but also left out some of the details like putting the text in the UITextField. 

I am usually comfortable manually writing all my UI Tests instead of using the recording feature. During this adventure I came across a weird error message: 

"UI Testing Failure - Neither element nor any descendent has keyboard focus on firstNumberTextField

The fix is to disable the "Connect Hardware Keyboard" from the Simulator Hardware menu and enable the "Toggle Software Keyboard". After that the UI Tests started working correctly. 

Happy coding! 

Emerging iOS Developers

I am finishing up week 6 of the iOS cohort at The Iron Yard Houston. I have been fortunate to have a group of extremely creative and talented students who are eager and passionate to learn iOS.  

I want to share some of my brightest students and products of their imaginations. 

Lists: 

Lists is a TODO list app created by Ryan Cortez. Lists allows you to manage your tasks by categorizing it into .. Lists. The easy to use interface and the ability to add multiple tasks to the list at one time makes Lists an awesome app. Lists is available on the App Store. 

Events: 

Events App allows you to schedule events and sync them with your calendar. The easy to use interface and wizard like flow of the app makes it a unique events scheduling application. Events is created by Ryan Cortez. Events will be available on the App Store very soon. 

Planets:

Matt Milner is the scientist behind the beautiful looking Planets application. The Planets application gives users useful information regarding each planet in our solar system. The app also exhibits the subtle yet effective animation effects which makes the solar system more realistic. 

Grocery App:

Toleen Jaradat is the developer behind the Grocery App. The grocery app allows the user to keep track of their lists and the related items in the list. Toleen used Core Data for persistent storage in her application. 

Looking back at my students I feel very proud of their accomplishments and I am eager and excited to see the applications they create in the future.

Iron Yard - Week 1 Recap

Last Friday I completed my first week at The Iron Yard as an iOS Instructor. My nine students might differ in the skill level but they all share the same passion for development. We started day 1 with a tour of Xcode and by the end of the first class they were managed to connect the IBOutlets and IBActions to make functional user interfaces. 

Each day begins with the review of the last assignment and then we jump into the lecture. Almost 90% of my lecture is live coding and 10% is drawing on the white board. Sometimes I throw in a 15-30 minute session of Round Robin. Round Robin is when I ask every student to come to the front and write part of the code. The next student continues where the last student stopped. I think this helps them think more clearly and loudly as they are in front of the other students. 

At the end of week 1 my students were able to make a Thermostat application which uses slider and segmented controls. 

Now, we are about end week 2 and I could not be more prouder with my students. They have definitely exceeded my expectations. I have no doubt in my mind that they will go in the real world and create beautiful, next generation of mobile applications. 

I would be lying if I say that being an iOS Instructor is an easy job. I have had many jobs in my life and I can easily say that this is the most toughest. I come home exhausted every day, but that is a good kind of exhaustion. The one that reflects that I am helping my students learn something new everyday, helping them get an awesome job and maybe even a whole new career. 

The toughest job in the world is also the best job in the world

WWDC 2016 Predictions

WWDC 2016 is just around the corner and the most fun thing you can do is to predict what will be revealed. Here are my predictions: 

  1. A Siri API will be released, allowing apps to communicate with the lady inside the phone.  
  2. I have been lucky enough to play around with Metaio SDK before Apple acquired it. Metaio provided easy to use APIs to easily create Augmented Reality applications. I am hoping that Apple will release a new Augmented and Virtual reality API based at WWDC 2016. 
  3. Apple has filed some patents on the virtual reality eye wear. I am predicting that Apple might announce a new device just like Google cardboard and Viewmaster which will allow users to have AR and VR experiences. 
  4. Devices like Amazon Echo has been gaining some traction. Google also announced Google Home at Google IO 2016. I am predicting that Apple will also step into this game with a new device powered by Siri. 
  5. Swift 3.0 will be announced.   

What I Learned from my Teachers?

In my last post I discussed why I joined The Iron Yard and why I am so interested in teaching. In this post I will discuss what I learned from my teachers. 

I have had a lot of teachers in my life but there are only a couple of teachers who made a very big impact. One of them was Sir Safdar, he was my Calculus I & II teacher in high school in Pakistan. Sir Safdar was an extremely strict teacher, who demanded structure and discipline in his class. Unlike other teachers his punishments were never physical beatings but more on the side of redoing the homework 3 times.  

I still remember one day I was showing him my homework and he asked me that why I have not listed the steps of solving the quadratic equations. I proudly told him that my brand new calculator is capable of solving quadratic equations by just inputting the values. He asked me to show him how the calculator does this magic and then he tore all the pages from my register and told me to do it all again, showing each step. 

One time he gave the class to solve 14 math problems. These were insanely hard questions and I could not even solve one of them. But I never gave up and tried and tried and after almost 6-8 hours I was able to solve 10 out of 14. On my way to his class I was terrified because I was not able to solve those remaining 4 problems. He looked at my register and said good work. I was surprised and told him that I was not able to solve all of them. What he said in reply changed my life forever.

He said "Azam, The reason I am NOT mad at you for not solving all the problems is because I can see in your register that you tried to solve it multiple times in different ways. You never gave up! And that is what I ask from my students, never give up on anything. Do your best and be happy with the result". 

I adopted the same principle when I was teaching Math and Computer Science to my fellow students. I asked them to show me where they have attempted to solve the problem and how many times they have failed. 

I hope I can also teach my students some life lessons, which they adopt in their professional as well as personal lives getting them closer to their dreams. 

Why Teaching?

Few days ago I was interviewing a potential student for the Mobile Engineering course at The Iron Yard. During our discussion the student asked me a very interesting question. He asked that why I decided to leave my cooperate job environment and become a teacher at The Iron Yard.

Here is my reply. 

I have been teaching in one form or the other for more than 16 years. I remember teaching my fellow classmates Physics and Calculus in high school. During my undergraduate years at University of Houston I started taking part in Microsoft forums and writing articles for CodeProject website. My first article about "Boxing and Unboxing in C# was widely received by the audience which gave me the motivation to move forward. During that time I also launched the website GridViewGuy which became extremely popular among .NET developers. GridViewGuy is now known as HighOnCoding. All in all I was spending 60-80 hours a week during college, learning new things, writing articles for websites including GridViewGuy, CodeProject, CoderSource.NET and ASPAlliance and also taking part in ASP.NET Forums

All this work finally paid off when I graduated and immediately got multiple offers from several different companies who heard about me through my websites. Later in 2006 I did my first public speaking for Houston .NET User Group. More than 100+ people showed by to listen to me talk about "Linq to SQL". After that speaking became fun for me and I spoke at Houston North .NET User Group, Houston TechFest, 360iDEV, 360iDEVMini etc. 

I also started a YouTube channel where I started teaching iOS development. Currently, the channel has more than 5000 subscribers. Few years ago I received an email from a YouTube subscriber, who told me that he is a teenager with autism and watches my channel to learn game development. This experience reminded me why I do what I do. 

I have always believed teaching to be a very noble profession. Your work as a teacher can literally change someone's else life in a better way. Apart from my parents I believe there are few teachers in my life who are responsible for where I am today and If I can become one of them then it will be priceless.

 

Joining The Iron Yard!

I am proud to announce that I will be joining The Iron Yard as an iOS Instructor in Houston, TX. I will be working with an already awesome team which comprises of Jesse Wolgamott, Matt Keas, Brian Dorton, Christie Loyd and Justin Richards. 

If I take a snapshot of my last 10 years, one thing is very clear that I love to share knowledge and I love to teach. I have always considered teaching a very noble profession which literally changes lives. 

After writing more than 1000 articles on HighOnCoding and doing countless speaking engagements and more than 350 videos I believe The Iron Yard is definitely the next step in my career. 

I am humbled and excited about this opportunity and looking forward to see how I can make a dent in the universe. 

Arrived++ has arrived!

Arrived++ is your premiere application for finding your things. Have you ever lost track of your luggage while traveling? How about parking in an unfamiliar part of town and keeping track of your vehicle? Have you ever missplaced your keys? Arrived++ can help you with all of these things and more!

Arrived++ uses a great new technology built into Particle, Estimote and Kontakt.io beacons. Simply attach one of the beacons to the item you want to keep track of and away you go!

We know you will love Arrived++, we do. The set up is easy with the codes on each beacon. Set Arrived++ to track an item when you want, and turn it off when you are done looking for your stuff to help keep battery usage low. It's all possible with Arrived++, so what are you waiting for?

Custom Swift Prefix Operator for background and foreground operations

Few days ago I was writing some demo code to run a long process while showing the activity indicator. The code ended up looking like the following: 

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
            self.somethingTimeConsuming()
            
            // update the UI 
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.activityIndicator.stopAnimating()
            })
        }

At this point if I want to do anything on the background again I have to write the similar code again. I thought what would happen if I create the prefix operator for background and foreground processes. Here is the implementation:

import UIKit

typealias EmptyClosure = () -> ()

prefix operator ~ {}
prefix operator ~~ {}

prefix func ~~ (closure: EmptyClosure) {
    
    dispatch_async(dispatch_get_main_queue()) { () -> Void in
        closure() 
    }
}

prefix func ~ (closure: EmptyClosure) {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
        closure()
    }
}

Now, I can rewrite my code like this: 

 ~{ // run on the background thread
            self.somethingTimeConsuming()
            
            ~~{ // run on the main thread
                self.activityIndicator.stopAnimating()
              }
            
        }

Much shorter but also not crystal clear!

The point of this post is not that you should start creating your operators but to show that you *can* create your operators and use them in meaningful scenarios. 

UIAlertController UITextField Bug

There are times when you want to display a UITextField inside the UIAlertController. You can use the following code: 

 @IBAction func openAddNewItemDialog() {
let alertController = UIAlertController(title: "Add New Item", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (action :UIAlertAction) -> Void in
            
if let textField = alertController.textFields?.first {                
    self.saveNewTask(textField.text!)
}
            
}))        
alertController.addTextFieldWithConfigurationHandler { (textField :UITextField) -> Void in
            
// configure the textbox
textField.placeholder = "Add new task"
}       
self.presentViewController(alertController, animated: true, completion: nil)
}

Unfortunately, the above code will lead to a message in the console as shown below: 

This is a bug in the UIAlertController and how it displays the UITextField. In order to silence the warning you can add the following just before presenting the controller. 

alertController.view.setNeedsLayout()
        

Happing coding!

Adding Toolbar for Number Pad in iOS

This is pretty old trick but since this question has been asked on StackOverFlow number of times I am going to cover it here. Let's say that you have a UITextField which shows a Number Pad. By default Number Pad does not gets dismissed since there is no "Return" or the "Done" button. We can easily add a UIToolbar as an accessory view of the UITextField which will allow us to add our own custom UIBarButtonItems. 

// create accessory view for the number pad 
let numberPadToolbar = UIToolbar(frame: CGRectMake(0,0,self.view.bounds.size.width,44))
numberPadToolbar.barTintColor = UIColor(fromHexString: "0B97FF")

numberPadToolbar.items = [UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "done:")]
        
self.majorIdTextField.inputAccessoryView = numberPadToolbar
self.minorIdTextField.inputAccessoryView = numberPadToolbar

The result is display below: 

Thoughts on Hourly Pricing

Couple of months ago I worked on an iPad application for a client. I cannot really discuss the technical details of the application but I can surely elaborate on the pricing models behind the application. 

As with most of the iOS developers I went with the hourly pricing model. I always thought hourly pricing model is the most financially viable pricing model of developers. The simplicity of the hourly models creates an illusion of profitability which is not uncovered by developers. 

I estimated the project would take 40 hours to complete. Let's say I charged X per hour that means 40 times X = revenue. But it also means if I complete the whole project in 20 hours then my profile will be half. So, in order to make the most money I have to deliberately ensure that I do not finish the project early even when it is possible

Don't worry I don't that bullshit! I actually completed the project in 20 hours meaning 20 hours under budget and delivered it on time. So, as you can see hourly pricing limits you in your income. First you have fixed hours in a day and in some scenarios you can finish the work early. 

At least finishing work early is good for your client. The other side of the equation is finishing the work late which is bad for you and your client. The client will be unhappy because you as a developer estimated the project wrong. And you as a developer will also be unhappy because now because of your bad estimate you have created a tension between yourself and the client.

Lucky for me I made my client happy by finishing the job early!

If you are a freelancer then think twice about charging hourly! A good alternative is value based pricing which I will cover in the future post!

Life after Parse!

Last week the iOS community mourned the loss of our beloved backend service, Parse. Parse was acquired by Facebook in 2013. At that time the acquisition sounded reasonable and developers saw it as a blessing as they knew that Parse needed a backing of a big company to survive. Unfortunately, even the Gods of Facebook could not save Parse from fading away. 

The whole Parse shutdown experience once again sparks the discussion on third party dependencies. From some people's point of view Parse is not directly connected to the business of Facebook and Parse does not provide financial motive to be continued by Facebook.

I agree with those people but It is also quite entertaining to watch that these reasons were never mentioned before the shutdown of the service. In the end Parse will shutdown and hundreds of thousands of developers who relied on it will scramble to find shelter for their backend. 

It seems that for a developer these third party services are no more than a mirage. They invite you with their neat API, thorough documentation and excellent support but once you reach closer to your destination, they vanish away. 

Some might argue that instead of depending on the non Apple services like Parse and Firebase developers should always use services part of the Apple echo system. Unfortunately, Apple is no exception to these casualties. Apple recently announced that they will be killing their advertisement service, iAds.

With that headline in mind would you consider implementing your backend service using CloudKit? Is the safest route to build the backend service yourself? How do you feel now about choosing a non Apple framework to build your iOS applications? 

Possible Bug: Swift Closures Unable to Infer Types

Let's take a very simple example! We have a struct called Person which is defined below: 

struct Person {
    
    var firstName :String
    var lastName :String
    var active :Bool
}

And it is populated with some dummy values using the code below: 

var persons :[Person] = []

for var i = 1; i<=10; i++ {
    
    var person = Person(firstName: "John \(i)", lastName: "Doe \(i)", active: true)
    persons.append(person)
}

Now, I want to change the active property from true to false using the map function .. So, I write the code like this: 

let inActivePersons = persons.map { (var p) in
    
    p.active = false
    return p
}

The above code results with the following error message: 

Cannot invoke 'map' with an argument list of type @noescape Person. 

The error can be fixed by explicitly adding the returned type as shown below:

let inActivePersons = persons.map { (var p) -> Person in
    
    p.active = false
    return p
}

But it only requires the return type if I am changing the value of the element. The following code will work and as you can see it does not have any return type: 

let inActivePersons = persons.map { (var p) in

    p
    
}

And even this will work: 

let inActivePersons = persons.map {
    
    $0
}

But this WILL NOT WORK: 

let inActivePersons = persons.map {
    
    print("Hmm")
    return $0
}

Another thing I noted is that when you are using $0 syntax in a closure there is no way to define $0 as a var variable! If there is please let me know! 

Protocol Extensions in Swift 2.0 for Beginners

Let's try to understand Protocol Extensions using a very simple story. Let's assume that we manage a circus which consists of different animals. One of those animals is a Dog. In order to represent dog we created a struct as defined below: 

struct Dog {
  
}

The Dog struct looks pretty boring! Let's add some functions to the struct. 

struct Dog {

    func eat() {
        print("I like to eat")
    }
    
    func sleep() {
        print("I like to sleep")
    }
    
}

Now, our Dog instance can eat and sleep using the following code: 

let dog = Dog()
dog.eat()
dog.sleep()

Everything is looking good! Your circus show was gaining attraction so you thought why not introduce a cat. Just like Dog struct you added a Cat struct as shown below: 

struct Cat {

  func eat() {
        print("I like to eat")
    }
    
    func sleep() {
        print("I like to sleep")
    }  
}

Something does not feel right about this implementation! I swear I have seen the eat and sleep functions somewhere else. Oh yeah! I have seen that in the Dog struct. DAMN this duplicating code! I can remove this duplicate code if I can find something common about the Dog and Cat. Hmm... they both have four legs, they both have a tail, they both like to eat grass ... thinking..thinking..thinking...... GOT IT! Both Dog and Cat can belong to a base struct called "Animal", since they both are animals. SWEEEEET!!

struct Animal {
    
    func eat() {
        print("I like to eat")
    }
    
    func sleep() {
        print("I like to sleep")
    }
}

Now, all I have to do is to inherit my Dog and Cat structures from the Animal structure and I will automatically get the eat and sleep features. 

struct Dog : Animal { 
}

Unfortunately, structures cannot inherit from non-protocol types. In other word structs cannot have base structs. This is an outrage! At this point you say FU** IT! I am using classes instead of structures. 

So, you changed all the structures into classes as shown below: 

class Animal {
    
    func eat() {
        print("I like to eat")
    }
    
    func sleep() {
        print("I like to sleep")
    }
}

class Dog : Animal {

    
}

class Cat : Animal {

    
}

let dog = Dog()
dog.eat()
dog.sleep()

let cat = Cat()
cat.eat()
cat.sleep()

SWEET!!! Now, my code is much cleaner! My dog and cat can really enjoy the circus. 

After a while someone mentioned that I can enhance my circus using birds. Ironically, I love birds so I decided to add birds to my code... YAWN.. How hard can it be? 

class Bird : Animal {
    
}

Consider it done! Oh wait I forgot to give birds the flying power! This is simple, I will just add a fly method in the Animal class as shown below: 

class Animal {
    
    func eat() {
        print("I like to eat")
    }
    
    func sleep() {
        print("I like to sleep")
    }
    
    func fly() {
        print("I can fly..")
    }
}

Unfortunately, adding to the Animal base class would mean that Dog and Cat entities will also have the flying capability as shown below: 

let bird = Bird()
bird.fly()

let dog = Dog()
dog.fly()

let cat = Cat()
cat.fly()

Well, maybe I can add that only to the Bird class. Let's do that: 

class Bird : Animal {
    
    func fly() {
        print("I can fly..");
    }
}

Sweet! Now only birds can fly and Dog and Cat cannot fly. And you are right it does works as expected! Unfortunately, you forgot about the Penguins that are shipped from Arctic. No problem Penguins are birds.. right. 

class Penguin : Bird {
    
}

DAMMIT! Penguins cannot fly! It would be nice if I have some contract which would indicate if the bird can fly or not. In Swift we can use protocols to create those contracts. 

protocol Flyable {
    func fly()
}

class Eagle : Bird, Flyable {
    func fly() {
        print("I can fly")
    }
}

class Penguin : Bird {
    
}

Now, Eagle can fly and Penguin cannot fly! Sweet! 

At this point your circus is getting a lot of popularity and you decided to include some more birds including Pelican, King Fisher, Sparrow etc. 

protocol Flyable {
    func fly()
}

class Eagle : Bird, Flyable {
    func fly() {
        print("I can fly")
    }
}

class Pelican : Bird, Flyable {
    func fly() {
        print("I can fly")
    }
}

class Sparrow : Bird, Flyable {
    func fly() {
        print("I can fly")
    }
}

Hmm.... Looks like repeatition! Eagle, Pelican and Sparrow can all fly. It would be nice to have some default implementation for the fly function which would be available to all the class that inherit the "Flyable" protocol. This is where "Protocol Extensions" jumps in. I know this article is like a movie where the main characters appears 10 minutes before the end of the movie. 

protocol Flyable {
    func fly()
}

extension Flyable {
    func fly() {
        print("I can fly")
    }
}

class Eagle : Bird, Flyable {
   
}

class Pelican : Bird, Flyable {
   
}

class Sparrow : Bird, Flyable {
   
}

Now, using the Protocol Extension we have a default fly method implementation. Anytime you call the fly method from the class which conforms to the Flyable protocol the default implementation will be called UNLESS the class itself defines its own implementation for the fly method. 

Also, you don't need those darn classes you can simply use structs and increase performance of your app as shown in the complete code below: 

//: Playground - noun: a place where people can play

import UIKit


protocol AnimalBehavior {
    
    func eat()
    func sleep()
}

extension AnimalBehavior {
    func eat() {
        print("I like to eat")
    }
    
    func sleep() {
        print("I like to sleep")
    }
}

struct Dog : AnimalBehavior {

    
}

struct Cat : AnimalBehavior {

    
}


protocol BirdBehavior : AnimalBehavior {
    
}

protocol Flyable {
    func fly()
}

extension Flyable {
    func fly() {
        print("I can fly")
    }
}

struct Eagle : BirdBehavior, Flyable {
   
}

struct Pelican : BirdBehavior, Flyable {
   
}

struct Sparrow : BirdBehavior, Flyable {
   
}

struct Penguin : BirdBehavior {
    
}

let dog = Dog()
dog.eat()
dog.sleep()

let cat = Cat()
cat.eat()
cat.sleep()

7 Minute Body

I have always been interested in working out and keeping myself fit. Even now I spend 6 days a week exercising which includes running, swimming and playing cricket. Actually, I am running a 10K on October 25 and a Half Marathon in January. In order to prepare for the marathons I have used a variety of apps which, included Nike Running, 7 Minute Workout etc.

The major pain point of using one of the 7 minute workout apps on your phone or watch was that the experience was not seamless. You always have to glance at the phone or the watch to see the remaining time, next workout etc. I always thought it would be great to run the app on the TV so it is right in front of you and you don’t have any distractions.

When Apple announced the new Apple TV I was delighted and overwhelmed with joy. The new Apple TV allowed developers to write apps for the big screen. Apple was also kind enough to send a number of developers an Apple TV Developer Kit which allowed us to test and run our apps on the actual tv.

Today it is my great pleasure to announce the release of my Apple TV app called “7 Minute Body”. As, the name suggest the app is directed towards health and fitness. 7 Minute Body provides the user with an easy to use interface, smooth navigation and intense workouts. 7 Minute Body also allows the users to listen to the current workout and notify them when to change sides. 

I have been using 7 Minute Body app for several weeks and keeping myself in great shape! I am sure this app will help you stay healthy and fit! 

Download 7 Minute Body now from the Apple TV App Store!

www.7minutebodyapp.com

How I Managed to Create 10 Apps While You Ate Your Lunch!

Most people know me as AzamSharp, the guy who runs the AzamSharp YouTube channel about iOS development. Occasionally, I speak at different conferences including 360iDev, Houston Tech Fest, 360iDevMini, Houston iPhone Meetup Group. Sometimes, I also publish iOS related articles in Code Magazine.

But, I bet no one is aware that my day job is not iOS development! At my day job usually I am working with Visual Studio, C#, ASP.NET MVC, JavaScript etc. To simply put my job revolves around Microsoft stack. This results in a very limited amount of time to learn, code and share iOS. 

Over the past 5 years I have been maintaining a very hectic schedule. I start my day by waking up at 4:30 - 5:00 AM in the morning. After a fresh cup of coffee I start working on my app! Since, I have only limited amount of hours before I have go to my work, I focus on very specific tasks that I want to achieve to move the app forward towards completion. Each pending task is reflected either on the sticky note or on my yellow notepad. It is not unusual that a single task might take couple of days for me to complete. Each task is also categorized by the version of the app! This makes it easier to set the app version feature set.

The story of the tortoise and the rabbit is a clear illustration of my iOS life. Just like a tortoise I move slowly towards the finish line. Each day I clear hurdles and make small progress towards my goal. The drive behind this madness is passion. Just like the human spirit it is hard to kill passion.

At present I have been able to publish 10 apps to the App Store. My app "Vegetable Tree - Gardening Guide" was even featured by Apple and is still considered the best vegetable gardening app on the app store. This personally made me very proud because it took me a long time to finish that app! But in the end just like a slow moving tortoise I managed to pass the finish line.

This post is for all the developers who are working part time on their passion projects. I just want to tell them that yes it is possible to publish apps even if you work 45-60 minutes a day.