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. 

360iDevMin Recap

360iDevMIN is an iOS developers conference held in heart of the beautiful city of Greenville, South Carolina. The "MIN" stands for mini, as compared to the 360iDev conference in Denver, CO. The great thing about a smaller conference is that it is very easy to interact with each other and if you have further questions you can always catch the presenter later.

People from all over the United States came for this conference. We even had Juliana came all the way from Brazil to educate us about accessibility in iOS. Juliana's talk was an eye opener as none of the attendees were implementing accessibility in their applications. Jay Thrash session on how to implement and change your user interface based on the device and orientation was also a great session. Jay showed how easy it is to use traits and size classes to create a new interface for iPhone 6 Plus Landscape mode. Melissa talked about new features in Swift 2.0, which is definitely going to help me write my next Swift 2.0 article for Code Magazine. 

I was also fortunate enough to give a talk about iBeacons at the 360iDevMIN conference this year, which was well received. Hopefully, we will see iBeacons more streamline in the industry. The 360iDevMIN was even mentioned in the local Greenville paper. 

Apart from the awesome sessions, the beautiful city of Greenville had lot to offer. The Falls Park on the Reedy is an absolute must attraction if you are in Greenville. The stream of water at the Falls Park follows the infinite trails around the park and makes the experience surreal and magical. 

Overall, everyone who attended 360iDevMIN had an amazing experience and I can't wait to come back next year and learn new stuff from really smart people!

Celebrate your App Launch!

I started developing for iOS in July 2010. My first app ABC Pop was created in 7 days without any prior knowledge of iOS development. On the 8th day I submitted the app to the App Store and started thinking about my next app. I never took the time to take a step back and reflect all the hard work I have done in creating, launching and marketing the app. It felt that I had no connection with the app and it was a just a mirage, which faded away with time. 

I continued the tradition of not celebrating the launch of my apps even when I invested a lot of time and hand work for their development. Vegetable Tree - Gardening Guide , which is considered the number one gardening app on the App Store was also the victim of silent celebration. Even when the Vegetable Tree was featured by Apple I never bothered to take a break and enjoy the moment.

At present I am working on an Apple TV app which I plan to release on the launch day of Apple TV, sometime late in October 2015. This time I intend to break my bad habit of not celebrating the launch. Also a celebration does not mean a 7 day cruise to Bahamas, but it can as simple as a chocolate cake or a family dinner at a nice restaurant. 

So, the next time you launch an app make sure you take a minute to enjoy the moment and reflect back on all the hard work you have done in creating a master piece! 

Yikes! I deleted the Objective-C Bridging Header

I have read countless posts where developers are stuck after deleting their Objective-C Bridging Header file. The bridging header basically provides a way for Swift code to call Objective-C code. If however you delete the bridging header by accident then your app will NOT compile. The reason it does not compile is because the app is still looking for that bridging header.

You can easily fix that by removing the Objective-C Bridging Header entry from the Build Settings.

Hope it helps! 

Swift Extensions Lacks @IBDesignable And @IBInspectable

@IBDesignable and @IBInspectable allows the developers to view their live rendering of their custom  controls. Recently, I had the need to make the rounded corners for the UIButton control. I thought instead of making a subclass of UIButton why not utilize the power of extension methods. 

Here is the implementation: 

import UIKit

@IBDesignable
extension UIButton {
   
    @IBInspectable
    public var cornerRadius :CGFloat {
        
        set { layer.cornerRadius = newValue }
        
        get {
            return layer.cornerRadius
        }
        
    }
    
}

Simple! The new property cornerRadius even appears in the Xcode properties window where I can adjust it. Unfortunately, the changes to the cornerRadius property are not rendered in real time but only when you run the app. 

Upon further investigation I found out that currently, the @IBDesignable and @IBInspectable live rendering is only supported on custom controls using subclasses. Hopefully, this feature will be extended to the Swift extensions in the future. 

Should You Learn Objective-C?

At WWDC 2014 Apple unveiled their new programming language, Swift. Swift language is a massive leap forward from its predecessor, Objective-C. Swift is a modern language which inherits many concepts from other popular languages including Go, Java, C#, Ruby etc. From the very start Apple made it clear that Swift is the path moving forward. At WWDC 2015 almost all of the sessions were delivered in the Swift language. 

At this point a common question on everyone's mind is that should I even learn Objective-C. Before answering this question with a simple YES or NO let me tell you my experience in development.

I have been developing professionally for more than a decade. During those years I worked at around dozen different companies ranging from oil and gas to health care. In those 10 years I can only recall couple of occasions where I worked on a *greenfield project. In all the other instances I was either fixing bugs or adding new features to the existing code base. Just last week I fixed some bugs on an iOS 4.0 application. 

The point I am trying to make is that although it might not be impossible to work on a brand new greenfield project, it is quite rare. This means most of the time you will be digging deep into the old codebase to either fix a bug or add a new feature. In iOS development this means you will be dealing with a lot of Objective-C code and which will be around for several future years.

So, to answer your question that whether you should learn Objective-C?

YES YOU SHOULD!     

*greenfield project means a brand new project where no lines of code has been written.