XCode 6 Beta 4 unimplemented IR generation feature bitcast between types of different size when archiving.

To temporarily resolve this until the next beta, change the compiler optimization level to None in the target’s release configuration. These settings can be found in Build Settings -> Swift Compiler-Code Generation

Screen Shot 2014-07-26 at 5.05.20 PM

Make a GET request with Swift, NSURLSession and NSURLSessionDataTask

Here’s how to Make a simple GET request in Swift using NSURLSession and NSURLSessionDataTask. First, we will create singleton that has access to a ‘network’ struct that has a computed property called session. We’ll also create an instance method called apiRequest(name:String, completionblock:(error:NSError, responseDictionary:NSDictionary)->()) in the singleton instance that has access to the network struct.

API.swift

public struct network {
    public var session:NSURLSession? {
    get {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        sessionConfig.HTTPAdditionalHeaders = //Dictionary here
        return NSURLSession(configuration: sessionConfig)
    }
    }
}

class API {
    class var sharedInstance : API {
    struct Static {
        static let instance : API = API()
        }
        return Static.instance
    }

//name argument isn't used in this method, 

    func apiRequest(name:String, completionblock:(error:NSError, responseDictionary:NSDictionary)->()) {
        let session = network().session!;
        let task : NSURLSessionDataTask = session.dataTaskWithURL(NSURL(string:"https://url_here"),completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
            NSLog(JSON!.description)
            return
            })
        task.resume()
    }
}

In your ViewController.swift file or another file that references the API class use this:


API.sharedInstance.apiRequest("name", completionblock: {(error: NSError, responseDictionary: NSDictionary) -> () in
//Set variables and do further processing here
 })

Detecting device shake using iOS 8 and Swift

To respond to a shake gesture in iOS 8 using Swift, you must override three methods in the ViewController that will respond to the shake: viewDidAppear(animated: Bool), canBecomeFirstResponder() -> Bool and motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!)


    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.becomeFirstResponder()
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent!) {
        if(event.subtype == UIEventSubtype.MotionShake) {
            var alert = UIAlertController(title: "Shaken",
                message: "Not Stirred",
                preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK",
                style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

Creating a Singleton in Swift – The Nested Struct Approach


class AppService : BaseService {
    class var sharedInstance : AppService {
        struct Static {
            static let instance : AppService = AppService()
        }
        return Static.instance
    }
}

While refactoring one of my apps recently, I had to figure out how to create a singleton in Swift. This approach seems like the most widely accepted way. The shared instance is a class variable. A closure is used to initialize and return a static instance that is contained in the nested Static struct within the closure. Oodles of joy. This is called the nested struct approach. There are two more which can be seen here:


https://github.com/hpique/SwiftSingleton

Dragging a CALayer

Put together a quick demo showing how to drag a CALAyer by capturing touch events and applying animations to the layer based on the position of the touches. Illustrates basic core animation concepts.

https://github.com/RTimal/CALayer-Drag

//
//  RTViewController.m
//  LayerTests
//
//  Created by Rajiev Timal on 3/7/14.
//  Copyright (c) 2014 Rajiev. All rights reserved.
//

#import "RTViewController.h"

typedef NS_ENUM(NSInteger, LayerState){
    LayerStateResting,
	LayerStatePickedUp,
};

@interface RTViewController ()

@property (nonatomic , strong) CALayer *topLayer;
@property (nonatomic , strong) CALayer *topLayer2;
@property (nonatomic, assign) LayerState currentLayerState;
@property (nonatomic, assign) CGPoint oldPoint;

@end

@implementation RTViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.topLayer = [CALayer layer];
	UIImage *appleImage = [UIImage imageNamed:@"applications-internet_full.png"];
	self.topLayer.contents = (__bridge id)([appleImage CGImage]);
	CATransform3D perspectiveTransform = CATransform3DIdentity;
	perspectiveTransform.m34 = -1/500.f;
	self.view.layer.sublayerTransform = perspectiveTransform;
	self.topLayer.position = CGPointMake(130.f,250.f);
	self.topLayer.bounds = CGRectMake(0.f, 0.f, 200.f,200.f);
	[self.view.layer insertSublayer:self.topLayer above:self.view.layer];


	self.topLayer2 = [CALayer layer];
	UIImage *appleImage2 = [UIImage imageNamed:@"applications-internet_full.png"];
	self.topLayer2.contents = (__bridge id)([appleImage CGImage]);
	CATransform3D perspectiveTransform2 = CATransform3DIdentity;
	perspectiveTransform2.m34 = -1/500.f;
	self.view.layer.sublayerTransform = perspectiveTransform2;
	self.topLayer2.position = CGPointMake(130.f,250.f);
	self.topLayer2.bounds = CGRectMake(0.f, 0.f, 200.f,200.f);
	[self.view.layer insertSublayer:self.topLayer2 above:self.view.layer];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[super touchesBegan:touches withEvent:event];
	CGPoint location = [[touches anyObject] locationInView:self.view];
	self.oldPoint = location;

	if(CGRectContainsPoint(self.topLayer.frame, location))
	{
		self.currentLayerState = LayerStatePickedUp;
		[CATransaction begin];
		[CATransaction setAnimationDuration:.5f];
		self.topLayer.zPosition = 40.f;
		self.topLayer.transform = CATransform3DRotate(self.topLayer.transform, .1, 0.f, 1.f,0.f);
		[CATransaction setCompletionBlock:^{
			self.topLayer.zPosition = 40.f;
			self.topLayer.transform = CATransform3DRotate(self.topLayer.transform, .1, 0.f, 1.f,0.f);
		}];

		[CATransaction commit];

		CABasicAnimation *spinningAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
		[spinningAnimation setFromValue:@0];
		[spinningAnimation setToValue:@30];

		CABasicAnimation *spinningAnimation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
		[spinningAnimation2 setFromValue:@0];
		[spinningAnimation2 setToValue:@30];

		CABasicAnimation *spinningAnimation3 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
		[spinningAnimation2 setFromValue:@0];
		[spinningAnimation2 setToValue:@30];

		CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
		[animationGroup setAnimations:@[spinningAnimation,spinningAnimation2, spinningAnimation3]];
		animationGroup.duration = 5.f;
		animationGroup.repeatCount = 1000000;
		[self.topLayer addAnimation:animationGroup forKey:@"spinXandYZ"];
	}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	[super touchesEnded:touches withEvent:event];
	if(self.currentLayerState == LayerStatePickedUp)
	{
		[CATransaction begin];
		[CATransaction setAnimationDuration:.5f];
		self.topLayer.zPosition = -40.f;
		[CATransaction setCompletionBlock:^{
			self.topLayer.zPosition = -40.f;
			self.topLayer.transform = CATransform3DIdentity;
		}];
		[CATransaction commit];
	}
	self.currentLayerState = LayerStateResting;
	[self.topLayer removeAllAnimations];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	[super touchesEnded:touches withEvent:event];
	CGPoint location = [[touches anyObject] locationInView:self.view];
	if((self.currentLayerState == LayerStatePickedUp) && CGRectContainsPoint(self.topLayer.frame, location))
	{
		[CATransaction begin];
		[CATransaction setAnimationDuration:0.f];
		self.topLayer.position =  CGPointMake(self.topLayer.position.x + (location.x - self.oldPoint.x), self.topLayer.position.y + (location.y - self.oldPoint.y));
		[CATransaction commit];
		self.oldPoint = location;
	}
}

@end

How To Become an Expert Programmer – Pick Yourself

Pick yourself

This piece of advice is from one of my favorite writers, Seth Godin. In this hyper-connected age everyone is poised to choose themselves. Want to be heard? Go online and write a blog post. Want to have your own company? Go to legalzoom.com, sign up for an LLC, and start selling your product or services. It’s become super easy for anyone to be an expert at anything. Set out to learn everything you can about something, and become an expert in it. Online course websites such as Coursera, Khan Academy, Lynda, and myriad more allow anyone to learn anything s/he wants whenever s/he wants. So, don’t wait for someone to pick you. Don’t wait for a some large company to come calling you. You have the power to choose yourself and start your expert training whenever and wherever you want.

http://sethgodin.typepad.com/seths_blog/2011/03/reject-the-tyranny-of-being-picked-pick-yourself.html

How to Become an Expert Programmer – Your ABC’s

Always Be Creating. It’s as simple as that. Reading about programming alone does not give you the experience or knowledge necessary to succeed. Experience helps your brain assimilate new information by forcing you to connect the dots between concepts and information using observation and inductive reasoning. In computer science, it’s all about what you create. Make a little app. Make a website. If you make one tiny app per week for a year, you’ll have 52 apps within one year. All of those one-off endeavors  can go on your resume and help you think like a programmer. Better yet, you can garner enough experience and know-how to start your own business. Create a blog post, create something. Many prolific programmers got their start in open source. What stops you from going out and creating your own open source project or contributing to someone else’s?  To be an expert programmer, problem solving through creation should be one of your life goals. No expert learns casually. Creating something every day forces you to think critically on a regular basis. Creation is not a casual exercise. It’s not like watching episodes of Breaking Bad or spooning with your girlfriend. Creating something forces you to think about the world in ways that you would have never thought of were you merely observing. Through building a bunch of little projects, your expertise will soar. Want to become a full stack engineer? Build a front-end web app one week, the next week build a php backend for it, the next week build an android app that also uses the backend, the next week build an iOS app that also makes simple requests to your backend. Wash, rinse, repeat with different languages and different technologies. The goal should be to hone your creative problem solving skills and just to absorb as much as you can about the intricacies of what you are doing and how you are doing it. If you want to be an expert programmer, one day should not pass in which you are not creating something. All that is left of us after we leave this earth is that which we create. Whether it be offspring, companies, legacies, or and app that improves the lives of 10 people, we have the power to create something every day. While doing this we can also become experts.  What did you create today?

502 Bad Gateway on nginx/1.2.6 using Elastic Beanstalk and Node.js

The quick fix for this is for express/http server  to listen on process.env.PORT,  not on a hard coded port (e.g. 3000). This can be accomplished in express by using

var express = require(‘express’);
var app = express();
app.set(‘port’, process.env.PORT || 8081);
…..
app.listen(app.get(‘port’));

 

I could not find any options or commands to configure the port for node in Elastic Beanstalk. At the moment, Nginx on an aws 64 bit linux instance is connecting to port 8081 to the node instance. process.env.PORT is set to 8081. When Express was listening on 3000 the bad gateway error was showing up. The logs/events provided by EB were useful to get to the root of this.

How to Become an Expert Programmer – Part 1

I am not an expert programmer nor do I claim to be one. I know that one day, I will be. I have immersed myself in the field for the past 9 months after leaving my previous career of 5 years. For some people, the following concepts come naturally and/or early on during childhood development. For others, they may come after years of practice. These are concepts that can be applied to any field, not just programming. Heres what I’ve learned, in no particular order of importance:

The Big Picture

Programming, or more appropriately, software engineering, is not about learning any particular language, it’s about representing and creating useful systems of varying size and complexity.  Systems that enrich peoples lives in some way. Systems that are maintainable, and in today’s world, scalable. Systems that can be maintained by others. Systems that are robust and do not become obsolete as soon as they are built.  Programming is more of a philosophy and a way of life than it is a traditional field of study. The act of architecting and building out complex programs is not tied to any particular programming language, and the skills needed are not specifically programming skills, but critical thinking skills. These can be developed just like any other skill.  The ability to analyze a problem, look at the inputs, outputs, the visible and invisible context, and make informed inferences and decisions transcends any particular programming language. This is the skill that will most benefit you as a software engineer.

Deliberate Practice

Programming, like anything, requires practice. However, one may find oneself practicing in vain if the type of practice isn’t conducive to learning and growth. Deliberate practice in programming means that you should scrutinize your code from every possible angle. I analyze every syntactical element when I’m coding, including how it relates to the rest of the program – even if it’s where a bracket should be placed. It’s easy to get into the automatic mode of copying and pasting lines of code from stack overflow and similar sites. This can be detrimental if you do not know how that code works on a deep level. You are not growing as a programmer if you do not know how your own code works. You should know what every method does, what parameters they accept, what outputs they return, what objects they belong to, when that object is used, what unique language features are being used (and why), etc. I can’t tell you how many times i’ve ignored the “virtual” keyword in C++  before I started practicing deliberately(and before my very kind co-worker told me what it was for). I now look up every unknown symbol encountered and try to commit its use and context to memory. Doing this enables you to learn increasingly difficult patterns and code styles without having to go back and look up what you’ve already seen – usually the building blocks of such complex patterns.

Style

Coding style is VERY important. Programming is not a lone activity, and no single person can create anything worthwhile and maintain it for it’s entire useful lifetime. Your code will be read by other people if it is to be of any value. This means that you should make it as readable as possible. There are syntactic guidelines for every language, even CSS(albeit not a traditional programming language). The high level structures created by the code also allows you to scan through them quickly. In Javascript, Java, and C++,  you  can tell where a block ends and begins just by the placement of the curly braces. Languages such as ruby and python don’t use curly braces, but there is still a recognizable structure to the code. I know programmers who can’t bare to look at poorly styled code. Its really just about being a good citizen and realizing that you are not the only one who has to deal with this code. Heres the objective-c style guide as an example : http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml

The Details

Every word you read can be qualified or quantified mentally. As you read something about programming, its easy to let your mind wander if that something is very boring. I found this happening to me while reading about the Android NDK. Not a very interesting subject at all(at least not while just learning it). To combat my waning attention span and to stop losing sight of the details, I decided to attribute something physical to each word I read. Heres a sample excerpt from the NDK documentation “A jni/ directory contains the native activity, main.c, which uses the android_native_app_glue.h interface to implement the activity. The Android.mk that describes the native module to the build system also exists here.” When reading this, you can think of a folder called JNI(maybe with “JNI” printed on it” ) –  a physical folder, with a physical file “main.c” in it – taking note of the word “main”  and the extension “.c” . And you can think of the other file, android_native_app_glue(taking a mental note of every word in this filename and the meaning behind every word) being physically used by main.c (maybe with main.c actually grabbing it with a hand in your mind’s eye) to implement the activity. And if your not sure what an “activity” is in that sentence, look it up right away. The same goes for “Android.mk”.  This may seem like common sense, but its easy to gloss over a detail represented by a particular unattractive looking word,  just to be stymied later by it and realize that it was a key piece of the puzzle. Take it all in, don’t let anything you read slide. The more symbolic representations you can create in your mind of these abstract concepts, the easier you will remember them. The human mind is meant to understand abstractions – after all, we do not see on a microscopic level, therefore everything we see and encounter in real life is an abstraction of some more complex system.

A Mentor

Find a mentor, someone who knows way more than you and has been doing this for years.  Your mentor should be able to tell you deep and hard to find secrets about the field that are only learned through years of hard work, toil, and experience. There is no shortcut to being an expert yourself, but no one is more qualified to lead  you on your path than another expert. Experts possess  a deep knowledge that allows them to see the field as a whole. With the details out of the way, they can see how the entire system  works and have unparalleled insight. Studies have  shown that expert tennis players can predict the direction of the ball before the other player hits it. They pick up on cues that the non-expert would not. They analyze the opponent’s posture, head and elbow position, stance, etc. and deduce where the ball will go. Knowledge like that can only be attained from an expert tennis player or from years of experience.

In the same Vein of finding a mentor, you should follow  well known experts in the field. Many of them have blogs, twitter accounts, numerous publications, and can even be accessed via email. Know who these people are, because they will shape your practice regardless of if you know of them or not. I don’t know a good javascript programmer who doesn’t know who Douglas Crockford is, and who hasn’t read his book: “Javascript: The Good Parts”.

Liquid Networks

Live in a big city and go to a lot of meetups. There is programming knowledge everywhere. Just go to meetup.com and look for groups of programmers. There are countless groups dedicated to specific languages, domains, operating systems, etc. Frequenting these meetups allows you to see what other people are doing and how they are approaching problems. Being in a bubble does not help any programmer. The proverbial programmer sits in his parent’s basement and codes his way to fame and success. This just doesn’t happen as often as people like to believe, and is very, very rare. Programmers need people too. Ideas are only attained through the minds of other people, and what better way to get ideas in this field than surrounding yourself with people who have ideas in the field?  Sort of a no brainer. You can combine the ideas attained from chatting with someone or hearing them speak with ideas from other people or ideas that you have gained through experience and practice.

On Programming Books

Books dedicated to a specific subject give deep expert insight – the same type that can be gained through a mentor. However, they are usually very very long and require a large amount of time to get through. I would only use a book if it is pertinent to a project that I am currently working on. And even then, only read the pertinent parts.  That way, I would be able to practice and therefore solidify the concepts that I learn in the book. Reading a programming book without practicing the concepts doesn’t produce much benefit. You may never even use the material and it will just fade away from your memory. Practicing it strengthens neuronal connections and ensures that you will remember it for the future. When I was working on my first objective-c project, I tried to read as many books as I could pertaining to what I was doing. After that was done, and I was on a Javascript project, I did the same. The concepts stick if you practice them while you learn them. Aside from programming language oriented books – there exists myriad theoretical texts that can give  you a strong foundation no matter what language you use. These are texts on algorithms, data structures, design patterns, domain driven design, refactoring, software architecture, software construction, etc. I’ll include a list below of some seminal texts that every programmer should read, regardless of her language of choice. Personally, I like reading SDK/API documentation. It’s a very useful skill to have because you will be using a LOT of other people’s code – unless you want to reinvent the wheel every time a new project comes about.

User Experience 

Always remember that you are making software for people to use. Take heed of who those people are and what they expect. Professional software should have a professional feel. An Image editing app will have a slicker user interface than an enterprise email client. UX is a whole other discipline, and people spend their entire professional careers designing cool user experiences. Every good programmer should have a sense of what is the right “feel” for what they are creating. This can come from working closely with UX people on a project or observing the finished work of others. Dribbble.com and Behance.net are some good places to find good work in design and UX.

Learn to use Google

Google doesn’t have all the answers. However, it does have most. Every programming language API documentation can be found through Google, and you can find many examples of their use on stackoverflow.com. The key to using Google is knowing exactly what to search for. I usually find that the simple approach works best. For example –  “Why is putImageData not working”. Search for the simplest way to express your problem. This will generally be how other people write about it and look for it. More than likely, you are not the only one who has experienced it. Once you get to a page that looks promising and may have your answer – follow the breadcrumbs. People may put links there with the solution to your problem. Keep digging deeper until you find it. If you can’t  find your answer, repeat the search again for another phrase or go to another result from the original phrase. Usually you can get what you want in the top 10 results if the right search phrase is used.

On Happiness, Passion and Love

One of the keys to happiness is to find something that you are deeply passionate about. If you  are deeply passionate about something, you will be intrinsically motivated to get better at it. No amount of money would make you stop doing it. The interesting part is that you will be so good at it just out of love for it, that money will come to you because of your expertise. Your passion and expertise will breed creativity and innovation in what you are doing. Many people flounder around without a passion. I was one of them. These people are just as intelligent and capable as people who have found their passion. Either they have not been motivated enough by anything to be good at it, or they have chosen not to explore their passions for extrinsic reasons. Doing something just for the money and doing it for love yields two very different levels of success. Once you find that thing(hopefully it’s programming 🙂 ), you will not need the lure of money, prestige, or any other extrinsic factors to keep getting better. Doing it just makes you feel good. If you are not passionate about software engineering, and you are just doing it to pay the bills, for job security, or because your parents pressured you into it, chances are you will never become an expert or be happy in what you are doing. The same goes for any field.

Conclusion

This is definitely not an exhaustive list of ideas and practices required to be an expert programmer, but they definitely help the cause.  Heres a tentative list of topic headings that I will write about in the future:

Create.

Hooks.

Create rules and constraints to get things done.

Build a mental model to hang things off of .

Think.

Open Source

Realize that all the information is there, its just a matter of finding it

Passing Data

Work on building mental pictures

Design Patterns, Algorithms, and Data structures

The idea Generation Trap

The expertise of others

Building prototypes

Learn by recursion

Don’t be afraid to fail

Work on one component at a time

 

If there are any questions , you notice any typos or grammatical errors, disagree or agree with me, please leave a comment :).

 

Reading Material that influenced this article:

http://www.amazon.com/Mastery-Robert-Greene/dp/0670024961

http://www.amazon.com/PP-Where-Good-Ideas-Come/dp/1594485380

http://www.amazon.com/Talent-Overrated-World-Class-Performers-ebook/dp/B001HD8NZ8

http://www.amazon.com/Am-Strange-Loop-Douglas-Hofstadter/dp/0465030793

 

Seminal works in software engineering that every good programmer should read

http://www.amazon.com/Design-Patterns-Elements-Object-Oriented-ebook/dp/B000SEIBB8 (Also known as the “gang of four” book)

http://mitpress.mit.edu/books/introduction-algorithms

http://www.amazon.com/Refactoring-Improving-Addison-Wesley-Technology-ebook/dp/B007WTFWJ6

http://www.amazon.com/Code-Complete-ebook/dp/B004OR1XGK

http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X

 

 

Great philosophy and insight into the world of startups: 

http://paulgraham.com/