Freelancing at Toptal | my first year!

2015 has been an amazing year for me and my family. It was the first full year of self employment and I have been very lucky to work with some amazing companies throughout the year. I wanted to write this post for others that are considering working for Toptal or maybe looking at something similar for work.

About me

I am a 29 year old iOS / web developer that has about 10 years of dev work experience. I have mostly worked for agencies building custom software for clients, but have also been at a couple start ups. I am happily married and have two beautiful daughters a 2 year old and a 6 month old. The freelancing life is a bit crazy at times and the uncertainty can be a little stressful especially when having to provide for a family. Toptal definitely takes some of that stress away by having a good amount of new clients coming through the pipeline.

The Toptal application process

Step 1 is to apply on the toptal website: Toptal.com depending on what position you are applying for I think determins how long it will take you to get an interview. My application went right through and I had an interview a couple days after applying.

The first interview is just a quick skype call. I think they mostly want to make sure your english skills are up to par as well as explain the interview process. If everything checks out you pass on to the next step at technical interview.

The technical interview is about an hour long and is just your standard run of the mil technical interview. My interview was with a javascript developer even though I applied as an iOS dev. He asked me to write a sorting algorithm and a question about a binary tree. They mostly want to see how you solve problems and what your thought process is.

Next up is the sample project. Since my background was mobile dev I elected to do the sample iOS app. It was a simple travel app that let you add, edit and delete trips that you were planning. They mostly checked for clean code, good standards and if you wrote tests. Once I passed this test I was hired!

Once you are hired

Once you are hired you get access to the Toptal system. You have to set up your profile, and add your experience and personal information. My Profile. You submit your profile for review and once approved you can start applying for engagements.

There are three types of engagements you can select from:

  • Full time a 40 hour a week contract
  • Part time a 20 hour a week contract
  • Hourly a flexible contract where you bill hours worked on the project

To apply for a contract you can browse all available engagements that meet your skill set.

Getting a project/engagement

The engagements vary a ton. There is everything from startups looking to supplement their teams to people that have an app idea that have no background in software development. Once you find an engagement that interests you, you can apply for the position. This application is sent first to a Recruiter that makes sure you would be a good fit for the position and then your profile is sent off to the client. If the client is interested they will request an interview.

Client interviews

The client interviews are super important. They are just as much for you as they are a client. You want to make sure their personality will be a good fit for you as well. The actual interview will vary depending on the client. I have had full technical interviews for start ups and super basic interviews from someone that has never built an app before. If you are a good fit you will be approved and a start date will be set.

Working with clients

Once you start you jump right into the project with the clients. I have really enjoyed working and integrating with teams that are more established software companies. I enjoy seeing their process for managing their code base and build processes. The most important part of maintaining a good relationship with clients is communication. Usually you will have a standup meeting that you join in everyday as well as getting access to their companies slack, or hip chat. The hours you work really depend on the company you are working for. I am located in the U.S. and was able to work for a company in London which is 8 hours ahead of me. I worked 4 am – 1 pm so I would catch the 12pm – 5 pm hours with the clients dev team. Usually though you have to have set hours.

Trial periods

There are trial periods for each of your engagements when you start out. Every time you start an engagement you get a trial period that starts on your start date. For a full time contract it is 10 business days, part time is 5 business days. You work on the project and once you hit the end of the trial period the client can either approve your engagement or cancel your engagement. If they cancel your engagement due to quality reasons they get a 100% refund and you are out of luck getting paid for those hours spent. If the work is good but it is a personality issue I think they get a 50% refund on the project. I haven’t had an issues with my trial period getting approved.

My overall thoughts on Toptal

Having worked in software development for a while this has definitely been my favorite gig. I really enjoy working for myself and having more control of how much money I make every year. If I ever need more money I can just pick up an extra part time contract for a couple weeks. The clients have been great, but I like I said before you need to make sure the client will be a good fit for you as well in the interview. It has also helped me learn about handling clients and how to present yourself to get them to treat you the way you want. I also love working from home. Having two little kids being around them throughout the day is amazing. I won’t lie at first there was stress about job security but really when you think about it a regular 9 – 5 job has just about no security. I think if you are good and dedicated at what you do there will always be people looking to hire you for your skills. There are also other stresses about health insurance and retirement and getting a mortgage (hopefully this year) and taxes that are a little more stressful but I think having more control over my life and happiness is way more beneficial than having those issue taken care for me by an employer. Toptal also has a pretty cool community. They have a slack community as well as live events you can go meet up with other developers in your area. Last winter I was invited to a ski trip up in Lake Tahoe, it was a blast and got to meet a bunch of cool people that work with Toptal. I think that Taso Du Val and Breanden Beneschott have really created an awesome company and I feel very lucky to be working with everyone at Toptal.

Should you Freelance with Toptal

I think freelancing is an awesome opportunity and Toptal definitely makes it a lot easier. You don’t have to do any marketing or billing and focus on development. They attract high quality clients and challenging projects. If you are looking to challenge yourself and grow as a developer I think Toptal is a good fit.

What I built this year with Toptal

I’m really proud of my work this year and wanted to brag a little about what I built!

  • Roomi – Find Roommates, Apartment Rentals & Sublets
    This was my first contract and I was really lucky to work with these guys. It was a really fun project to work on and I learned a lot.
  • House of Fraser
    The house of fraser app is my favorite app I’ve built in a long time. The team I got to work with was top notch and their code quality was amazing. I really enjoyed integrating with their team and learning there code testing and reviewing process. I also got to build a bar code scanner and the project was written in Swift. Just a lot of fun to work on.
  • Zugata
    Zugata is an awesome company located in Palo Alto and I feel really lucky to be working with them. They are a small and dynamic team with great leadership. I have really enjoyed working with such a small and energetic team and I have learned so much from them. I am also really excited this is a longer term engagement and will hopeful get to work with them for most of the next year and maybe even longer. I can’t wait to see what we will build together.

It has been a really exciting year and I can’t wait to see what 2016 will bring! If you have any questions about Toptal or anything about freelancing in general then please feel free to leave a comment below or follow me on twitter and send me a tweet.

D3 / JavaScript Swift & iOS | JavaScriptCore Framework

Why would you ever want to use JavaScript in your Swift Project?

javascript-sucks I am working on a project that started off as a web application first. It has a lot of cool features and some pretty advanced graphs. Their front end developer is using d3.js. D3.js is a JavaScript library for manipulating documents based on data. D3 is an amazing library that can do just about any kind of graph imaginable from circle packing to basic line graphs, and what is even more impressive is it was written by one guy Mike Bostock. Anyway in addition to awesome graphs there are a lot of helpful functions for calculating all kinds of data, and the front end developer on my project was using these. I thought no problem I can just translate these methods into swift and be able to reproduce the same data! Easy peasy lemon cheesy right. Wrong… Mike Bostock is a genius and I found out how incompetent I am at math!

A real world application

So in this application there is a graph that displays your co workers based on how much you interact with them based on email and slack conversations. The data base returns a score with each contact from 1 to 10 and according to that score the user is place in one of three rings the circle closet to you being those that you work with the most and the outer circle being the one that you work with the least. D3 has some really handy Quantitative Scales that the front end developer used to get which circle the co worker should be placed in. So after hours of trying to figure out how the hell Mike wrote these awesome scales I decided to embrace my hate, turn to the dark side and just use javascript in my project.
ain't nobody

JavaScriptCore Framework

Available since iOS 7 JavaScriptCore is the built-in JavaScript engine for WebKit. It currently implements ECMAScript as in ECMA-262 specification. It allows for an easy and fast way to interact with JavaScript.
To get started you first need to load in the d3 library. Also in this first step we are going to add error handling so we are able to see what we are doing wrong with our javascript which can be very handy!

// get a reference to the d3 library in our project
let fileLocation = NSBundle.mainBundle().pathForResource("d3.min", ofType: "js")!
// convert it to a string
let jsSource: String = try! String(contentsOfFile: fileLocation)
// create a javascript context environment
let context = JSContext()
// add exception handler so we can see any error that occur in our javascript
context.exceptionHandler = { context, exception in
    print("JS Error: \(exception)")
}
// load in the javascript into our context
context.evaluateScript(jsSource)

Once d3 is loaded we can access it exactly like you would in a HTML file

// create our javascript function for the linear scale we also mix in swift with the maxAmount variale
context.evaluateScript("circles = d3.scale.quantize().domain([0,\(maxAmount)]).range([3, 2, 1])")

// loop through all the contacts to determine which circle they should be placed in
for contact in contacts {
    // get the circle number based on score it will return 1, 2 or 3
    let circle: JSValue = context.evaluateScript("radius_circles(\(contact.score))");
    //  cast the JSValue to Int
    contact.circle = Int(circle.toInt32())
}
// sort the contacts array based on the new circle value
self.contacts.sortInPlace({ $0.circle < $1.circle })

Success

Thats all there is to it! Now we have data that matches the web app so we can successful show the same rankings and data in the iOS app! I don't think I would use this very often but I think it is very handy to have as an extra tool in your tool box. Let me know in the comments below what you guys think to this approach and if you would ever use javascript in your project

Lets be friends

I love meeting new iOS friends online so follow me on twitter
. Please stop by and say hello!

Dynamic UITableViewCell Height | Swift

Working as an iOS developer since iOS 4 I have been able to see lots of changes like the introduction of ARC, auto layout, storyboards, size classes and swift. Working for agencies I am always amazed at how long it takes some companies to adopt these new tools, a lot of which make your life easier and reduce the amount of code you have to write. Today I’m going to be talking about how easy it is to create a UITableViewCell that has a dynamic height based on the content in the cell using Auto Layout. If you want to follow along with project you can download the it from github. Also if you have any questions send me a tweet over at
or leave a comment below.

Setting up the UITableViewCell

First thing we do is set up the view. I have a UITableView in my view and since I’m using a storyboard I can prototype the cell right in the table view. I add two UILabels that will hold the cell’s content. Here is what we have so far:
Storyboard with UITableView and prototype cell
Next we need to add the constraints to the labels. Since we want them to resize depending on how much text is in them we are going to set leading, trailing, top, and bottom spacing constraints. The First Label will look like this:
Screen Shot 2015-04-05 at 2.19.36 PM
And the second label’s constraints will look like this:
Screen Shot 2015-04-05 at 2.22.13 PM
The constraints in Label 1 are letting the view know each label has a margin of about 8 points to the top, leading and trailing spacing and another 8 points to the label below it. So now matter how the height of the label to keep it spacing. The constraints in Label 2 are doing pretty much the same thing except the top spacing is referring to the label above it and the bottom spacing is referring to the parent view.

Don’t forget to set the number of lines in the label to 0 and line breaks to word wrap so the label can have multiple lines of text

Setting up the UITableView

In the view controller we created an IBOutlet for the table view and there is only one thing we have to do differently and it’s letting the talbe view know it will be using dynamic heights for each cell.

self.tableview.rowHeight = UITableViewAutomaticDimension 

Once that is done we just handle it like a normal UITableView and UITableViewCelll no need to sizeToFit or calculate height for heightForRowAtIndexPath! Here is what the completed ViewController looks like:

//
//  ViewController.swift
//  Dynamic-Cell-Height
//
//  Created by Barrett Breshears on 4/5/15.
//  Copyright (c) 2015 Barrett Breshears. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableview:UITableView!
    var tableViewData:[String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableview.rowHeight = UITableViewAutomaticDimension 
        
        self.tableViewData.append("Bacon ipsum dolor amet venison pork chop beef tri-tip meatball andouille. Biltong cupim turducken turkey pig, picanha shankle porchetta salami ham hock venison. Bresaola salami sausage corned beef jowl meatball spare ribs chuck short loin chicken. Bacon ham hock swine leberkas salami porchetta kielbasa shankle.")
        self.tableViewData.append("Landjaeger ham hock kevin shankle, sirloin bacon jowl meatball tail. Frankfurter ham chicken corned beef meatloaf ground round pork loin turkey tenderloin cow pork filet mignon bacon short ribs jerky. Drumstick bresaola picanha tail. Ribeye tail landjaeger, sausage pork belly biltong flank shank fatback cow meatloaf. Frankfurter short loin pancetta turkey t-bone, pork chop sirloin. Sirloin pork loin boudin spare ribs pastrami. Pig brisket sirloin chuck turkey.")
        self.tableViewData.append("Spare ribs cupim prosciutto hamburger kevin strip steak pastrami bresaola ham turducken pork kielbasa picanha. Cupim strip steak chicken pork belly beef ribs. Pork chop strip steak flank tenderloin short loin bacon corned beef cupim ground round venison doner ham chicken tail beef. Corned beef cupim tenderloin doner prosciutto filet mignon. Tail ham hock ham hamburger shankle landjaeger sirloin, brisket tongue t-bone pork. Beef ribs porchetta alcatra hamburger, chicken filet mignon ground round ham ball tip shank turducken pork chop. Ham hock venison t-bone frankfurter prosciutto, doner drumstick shankle ball tip tenderloin ribeye.")
        self.tableViewData.append("Frankfurter ham spare ribs turducken venison biltong. Tenderloin kevin flank pork loin capicola. Pastrami tenderloin kevin, turducken beef ribs salami cupim short ribs. Pork flank cupim, meatloaf tail leberkas tri-tip filet mignon tenderloin turducken beef salami.")
        self.tableViewData.append("Doner ball tip meatball shoulder tongue shankle chicken. Ground round turducken kielbasa, chicken meatloaf flank corned beef chuck rump hamburger spare ribs. Beef ribs pork belly filet mignon meatloaf, corned beef andouille tri-tip jerky turkey biltong alcatra ham hock. Alcatra meatloaf capicola, drumstick cupim spare ribs boudin meatball kevin cow ribeye porchetta beef ribs. Cupim alcatra beef pork chop pork belly ground round capicola salami turkey shankle tenderloin chicken frankfurter landjaeger. Cow hamburger meatloaf pancetta bacon rump, venison pork belly kielbasa kevin.")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as? CustomTableViewCell;
        
        var data:String = self.tableViewData[indexPath.row] as String!
        cell?.label1.text = data
        cell?.label2.text = data
        
        return cell!;
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableViewData.count
    }
    

}

Thats it! I think this simple example really shows how much you can do with Auto Layout, and if you have been to busy or just more comfortable using springs and struts you consider learning Auto Layout and constraints. If you enjoyed this post I would really appreciate it if you share it with your friends. Also I am always looking for iOS developer friends follow me on twitter and send me a tweet if you ever want to talk about anything, please no android developers (just kidding).

AWS S3 Image upload using AWS SDK for iOS v2

Hi there and welcome. Today we will be talking about AWS S3 Image upload using AWS SDK for iOS v2 (WOW thats a lot of acronyms!). Last week I had to do this in a project and it took me and I was disappointed with the documentation, and sample project they had available. So in this tutorial I’m going to be showing a real world example where you would select an image from the gallery or take a photo on a device and upload that image to your bucket. If you want to follow along I have the projects available on github for both objective-c and swift! I also have a video of setting up S3 and Amazon Cognito at the end of the tutorial, but I have to apologize for the quality. I am terrible at making videos, and I was very tired when I made it (also my voice is very annoying).

Github Links

Also don’t forget to follow me on twitter if you ever want to chat about iOS or mobile development! .

Set up credentials

First thing we need to do is set up amazons credentials your app delegate’s didFinishLaunchingWithOptions method. In this demo we are going to use Cognito to manage access to our S3 bucket. If you want a full in depth look at how to do this watch the video at the end of the tutorial.

Objective-C

AppDelegate.m

//
//  AppDelegate.m
//  s3-objectiveC
//
//  Created by Barrett Breshears on 12/5/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

#import "AppDelegate.h"
#import "AWSCore.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    AWSCognitoCredentialsProvider *credentialsProvider = [AWSCognitoCredentialsProvider
                                                          credentialsWithRegionType:AWSRegionUSEast1
                                                          accountId:@"#######"
                                                          identityPoolId:@"######"
                                                          unauthRoleArn:@"#####"
                                                          authRoleArn:@"######"];
    
    AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1
                                                                          credentialsProvider:credentialsProvider];
    
    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

@end

Swift

AppDelegate.swift

//
//  AppDelegate.swift
//  s3-swift
//
//  Created by Barrett Breshears on 12/6/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        var credentialsProvider:AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider.credentialsWithRegionType(AWSRegionType.USEast1, accountId:"##########", identityPoolId:"#######", unauthRoleArn:"#######", authRoleArn:"########")
        
        var configuration:AWSServiceConfiguration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
        
        AWSServiceManager.defaultServiceManager().setDefaultServiceConfiguration(configuration)
        
        
        
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
    }

    func applicationDidEnterBackground(application: UIApplication) {
    }

    func applicationWillEnterForeground(application: UIApplication) {
    }

    func applicationDidBecomeActive(application: UIApplication) {
    }

    func applicationWillTerminate(application: UIApplication) {
    }


}

This is a pretty simple set up here, and if you configure your credentials in the Cognito console it will actually give you the code to set up your configuration.

Upload an image to S3

So the main difference between v1 and v2 is that you used to be able to set the upload body request to NSData or a NSURL. In v2 you can only set the upload request to a NSURL. So what we have to do is save the image to the app’s local directory and then we can create a local file url to send to amazon.

Objective-C
- (void)uploadToS3{
    // get the image from a UIImageView that is displaying the selected Image
    UIImage *img = _selectedImage.image;
    
    // create a local image that we can use to upload to s3
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"image.png"];
    NSData *imageData = UIImagePNGRepresentation(img);
    [imageData writeToFile:path atomically:YES];
    
    // once the image is saved we can use the path to create a local fileurl
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    
    // next we set up the S3 upload request manager
    _uploadRequest = [AWSS3TransferManagerUploadRequest new];
    // set the bucket
    _uploadRequest.bucket = @"s3-demo-objectivec";
    // I want this image to be public to anyone to view it so I'm setting it to Public Read
    _uploadRequest.ACL = AWSS3ObjectCannedACLPublicRead;
    // set the image's name that will be used on the s3 server. I am also creating a folder to place the image in
    _uploadRequest.key = @"foldername/image.png";
    // set the content type
    _uploadRequest.contentType = @"image/png";
    // we will track progress through an AWSNetworkingUploadProgressBlock
    _uploadRequest.body = url;
    
    __weak ViewController *weakSelf = self;
    
    _uploadRequest.uploadProgress =^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend){
        dispatch_sync(dispatch_get_main_queue(), ^{
            weakSelf.amountUploaded = totalBytesSent;
            weakSelf.filesize = totalBytesExpectedToSend;
            [weakSelf update];
            
        });
    };
    
    // now the upload request is set up we can creat the transfermanger, the credentials are already set up in the app delegate
    AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
    // start the upload
    [[transferManager upload:_uploadRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
        
        // once the uploadmanager finishes check if there were any errors
        if (task.error) {
            NSLog(@"%@", task.error);
        }else{// if there aren't any then the image is uploaded!
            // this is the url of the image we just uploaded
            NSLog(@"https://s3.amazonaws.com/s3-demo-objectivec/foldername/image.png");
        }
        
        return nil;
    }];
    
}
Swift
 func uploadToS3(){
        
        // get the image from a UIImageView that is displaying the selected Image
        var img:UIImage = selectedImage!.image!
        
        // create a local image that we can use to upload to s3
        var path:NSString = NSTemporaryDirectory().stringByAppendingPathComponent("image.png")
        var imageData:NSData = UIImagePNGRepresentation(img)
        imageData.writeToFile(path, atomically: true)
        
        // once the image is saved we can use the path to create a local fileurl
        var url:NSURL = NSURL(fileURLWithPath: path)!
        
        // next we set up the S3 upload request manager
        uploadRequest = AWSS3TransferManagerUploadRequest()
        // set the bucket
        uploadRequest?.bucket = "s3-demo-swift"
        // I want this image to be public to anyone to view it so I'm setting it to Public Read
        uploadRequest?.ACL = AWSS3ObjectCannedACL.PublicRead
        // set the image's name that will be used on the s3 server. I am also creating a folder to place the image in
        uploadRequest?.key = "foldername/image.png"
        // set the content type
        uploadRequest?.contentType = "image/png"
        // and finally set the body to the local file path
        uploadRequest?.body = url;
        
        // we will track progress through an AWSNetworkingUploadProgressBlock
        uploadRequest?.uploadProgress = {[unowned self](bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
            
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                self.amountUploaded = totalBytesSent
                self.filesize = totalBytesExpectedToSend;
                self.update()

            })
        }
        
        // now the upload request is set up we can creat the transfermanger, the credentials are already set up in the app delegate
        var transferManager:AWSS3TransferManager = AWSS3TransferManager.defaultS3TransferManager()
        // start the upload
        transferManager.upload(uploadRequest).continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock:{ [unowned self]
            task -> AnyObject in
            
            // once the uploadmanager finishes check if there were any errors
            if(task.error != nil){
                NSLog("%@", task.error);
            }else{ // if there aren't any then the image is uploaded!
                // this is the url of the image we just uploaded
                NSLog("https://s3.amazonaws.com/s3-demo-swift/foldername/image.png");
            }
            
            self.removeLoadingView()
            return "all done";
        })
        
    }

Once you understand how to configure your credentials and how to get the image from an image view to local file to url to amazon the process is pretty simple. Please let me know if you have any questions in the comments below or on send me a tweet
.

Setting up credentials and project walk through video

Create Custom Delegate and Protocol iOS | Swift & Objective-C

One of the most powerful tools an iOS developer has is the ability to create protocols and implement delegates that let your classes notify when an event occurs. I use them all the time in my projects and wanted to show how easy it is to implement your iOS Project. I will demonstrate them in both Objective-C and Swift so you can see a side by side comparison. In this example we will be implementing timer that fires a timerFinished method to let the UIViewController know the timer finished and start the timer over.

If you want to follow allow you can download the projects from GitHub here:

Objective-C  Project
Swift Project

Protocols

A protocol is a list of methods that specify an interface that your delegate will implement. There are two kinds of delegates we can use: Option and Required. They are pretty self explanatory but the difference is Required will throw an error letting you know your class is not conforming to the protocol. Also protocol methods are required by default so if you want it optional don’t forget that optional keyword. If you are using swift you will also need to add the @objc prefix if you want an optional method.

Swift
//
//  MyTimer.swift
//  SwiftProtocol
//
//  Created by Barrett Breshears on 10/11/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

import UIKit

// set up the MyTimerDelegate protocol with a single option timer finished function
@objc protocol MyTimerDelegate{
    optional func timerFinished()
}


class MyTimer: UIViewController {
    
    // this is where we declare our protocol
    var delegate:MyTimerDelegate?
    
    // set up timer variables and labels
    var timer:NSTimer! = NSTimer()
    var labelTimer:NSTimer! = NSTimer()
    var timerLabel:UILabel! = UILabel()
    var timerCount = 0
    var duration = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        timerLabel = UILabel(frame: self.view.frame)
        timerLabel.textAlignment = NSTextAlignment.Center
        self.view.addSubview(timerLabel)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func startTimer(timerDuration:Double){
        self.duration = Int(timerDuration)
        timerLabel.text = String(format: "%d", duration)
        
        timer = NSTimer.scheduledTimerWithTimeInterval(timerDuration, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: false)
        
        labelTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateLabel:"), userInfo: nil, repeats: true)
        
        
    }
    
    func timerFired(timer:NSTimer){
        if(timer.valid){
            timer.invalidate()
        }
        if(labelTimer.valid){
            labelTimer.invalidate()
        }
        // ************************************** \\
        // ************************************** \\
        // This is the important part right here
        // we want to call our protocol method
        // so the class implementing this delegate will know
        // when the timer has finished
        // ************************************** \\
        // ************************************** \\
        delegate?.timerFinished!()
        
    }
    
    func updateLabel(timer:NSTimer){
        duration = duration - 1
        timerLabel.text = String(format: "%d", duration)
    }
    
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */
    
}

This is a pretty simple example but here is what is going on. The UIViewController has a start timer method that sets up the two timers: one that will fire when the overall time is complete and one that fires every second to update the timer label. When the total duration timer is finished the timerFired method is called, and thats where we run the delegate’s timerFinished method. Now lets do the same thing but with Objective-C.

Objective-C
//
//  MyTimer.h
//  ObjectIveCProtocol
//
//  Created by Barrett Breshears on 10/11/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

#import 

// set up the MyTimerDelegate protocol with a single option timer finished function
@protocol MyTimerDelegate 

@optional
-(void)timerFinished;

@end

@interface MyTimer : UIViewController
// this is where we declare our protocol
@property (nonatomic, strong) id delegate;
// set up timer variables and labels
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *labelTimer;
@property (nonatomic, strong) UILabel *timerLabel;
@property (nonatomic, assign) int timerCount;
@property (nonatomic, assign) int duration;

- (void)startTimer:(float)duration;

@end

//
//  MyTimer.m
//  ObjectIveCProtocol
//
//  Created by Barrett Breshears on 10/11/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

#import "MyTimer.h"



@interface MyTimer ()

@end

@implementation MyTimer

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _timer = [[NSTimer alloc] init];
    _labelTimer = [[NSTimer alloc] init];
    _timerCount = 0;
    _duration = 0;
    
    
     _timerLabel = [[UILabel alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_timerLabel];
    [_timerLabel setTextAlignment:NSTextAlignmentCenter];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)startTimer:(float)duration{
    _duration = (int)duration;
    _timerLabel.text = [NSString stringWithFormat:@"%d", _duration];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:duration
                                              target:self
                                            selector:@selector(timerFired:)
                                            userInfo:nil
                                             repeats:NO];
    
    _labelTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(updateLabel:)
                                                 userInfo:nil
                                                  repeats:YES];
    
    
}

- (void)timerFired:(NSTimer *)timer {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
    if ([_labelTimer isValid]) {
        [_labelTimer invalidate];
    }
    _labelTimer = nil;
    // ************************************** \\
    // ************************************** \\
    // This is the important part right here
    // we want to call our protocol method here
    // so the class implementing this delegate will know
    // when the timer has finished
    // ************************************** \\
    // ************************************** \\
    [_delegate timerFinished];
}

- (void)updateLabel:(NSTimer *)timer{
    _duration = _duration - 1;
    _timerLabel.text = [NSString stringWithFormat:@"%d", _duration];
}

@end

So same thing just different syntax. The UIViewController has a start timer method that sets up the two timers: one that will fire when the overall time is complete and one that fires every second to update the timer label. When the total duration timer is finished the timerFired method is called, and thats where we run the delegate’s timerFinished method.

Delegates

Now that we have our protocols all set up all we have to do is implement them. We are going to do this by creating a delegate. A delegate is a variable that complies to a protocol, which a class typically uses to notify of events, in this case the timer finishing. To do this we add our protocol to our class declaration, to let our class know it must comply with the delegate. Then we add our delegate method to our class.

Swift
//
//  ViewController.swift
//  Swift-Protocol
//
//  Created by Barrett Breshears on 10/11/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

import UIKit

// add our MyTimerDelegate to our class
class ViewController: UIViewController, MyTimerDelegate {
    
    var timer:MyTimer = MyTimer()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        timer.view.frame = self.view.frame
        // ************************ \\
        // This is where we let the delegate know 
        // we are listening for the timerFinished method
        // ************************ \\
        timer.delegate = self
        self.view.addSubview(timer.view)
        timer.startTimer(10.0)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // ************************ \\
    // This is where our delegate method is fired
    // ************************ \\
    func timerFinished(){
        timer.startTimer(10.0)
        println("Hey my delegate is working")
    }

}

So the important thing here is we set the timer.delegate to self so the ViewController’s method timerFinished() class is called.

Objective-C
//
//  ViewController.h
//  ObjectIveCProtocol
//
//  Created by Barrett Breshears on 10/10/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

#import 
#import "MyTimer.h"

// add our MyTimerDelegate to our class
@interface ViewController : UIViewController 

@property (nonatomic, strong) MyTimer *timer;

@end
//
//  ViewController.m
//  ObjectIveCProtocol
//
//  Created by Barrett Breshears on 10/10/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _timer = [[MyTimer alloc] init];
    _timer.view.frame = self.view.frame;
    _timer.delegate = self;
    [self.view addSubview:_timer.view];
    [_timer startTimer:10.0];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)timerFinished{
    [_timer startTimer:10.0];
    NSLog(@"Hey my delegate is working!");
}

@end

When we run the code we see the timer label is added and set to a 10 second timer. It counts down, and when it reaches 0 it notifies the viewcontroller, restarts the timer and prints the “Hey my delegate is working in the console”.

If you have any questions about the code or found this tutorial helpful let me know in the comments below! I appreciate feedback. Also don’t forget to follow me on twitter. I am always looking for iOS developers to tweet with.

CoreLocation iOS 8 and Swift

I started my first swift app with iOS 8 and needed to use core location, something that I haven’t used in a really long time. After writing all the code and testing out the app I couldn’t get the dang thing to use my location! After a frustrating 30 min of debugging I figured out what the issue is and decided to write this post to hopefully help you avoid that frustration. So here is what you need to do to get core location working with iOS 8 and swift.

CoreLocation Project setup

Add the CoreLocation.framework to your project

First step is to select your project in the project navigator, and select your project target. Once selected expand the link binary and click the add items button. Choose the CoreLocation.framework from the pop up window.
Screen Shot 2014-10-09 at 7.14.55 AM

Editing Info.plist

This is where I screwed up in my attempt, I forgot to add the property key in my plist. This caused the app not to get my location, and it didn’t give any warning or error to let me know there was even a problem. So add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription key in your Info.plist file to indicate the level of authorization you require. NSLocationWhenInUseUsageDescription will allow you to get the device location when you are using the app and NSLocationAlwaysUsageDescription will allow you to get the device location when you are using the app as well as in the background when the app isn’t running. The key you set is what will be displayed in the pop up asking for permission. Also as a side note if you need to localize your plist here is apple’s docs on how to do that Localizing Property List Values. I only need to use location while the app is in use so I used NSLocationWhenInUseUsageDescription and only wanted apple’s default message so I left the value blank.
Screen Shot 2014-10-09 at 7.37.09 AM

Create your view controller and add the CLLocationManagerDelegate

Now that we have all that project setup done we can get on to the code. So first step is to add the CLLocationManagerDelegate to your view controller, implement these delegate methods. Then init your CLLocationManager and start receiving your location data.

//
//  MapViewController.swift
//
//  Created by Barrett Breshears on 10/6/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

import UIKit
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        } else {
            println("Location services are not enabled");
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK: - CoreLocation Delegate Methods
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        locationManager.stopUpdatingLocation()
        removeLoadingView()
        if ((error) != nil) {
            print(error)
        }
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        println(coord.latitude)
        println(coord.longitude)
    }
}

Let me know if there are any questions or comments about the code or the project setup. Also don’t forget to follow me on twitter! I’m always looking for new internet friends.

3d printed iPhone stencil for protyping

I got my Printrbot simple about 6 months ago, and love it. Ever since I have got it I have been trying to figure out something cool to make. Last week I saw an ad for an iPhone stencil made out of metal, and thought is was pretty sweet http://www.uistencils.com/products/iphone-stencil-kit. I thought to myself hey I have a 3d printer, I can make things like this! I download things from thingiverse all the time how hard could it be! Well it wasn’t easy and I’m sure there are better ways of doing this. If you enjoy this awesomeness please follow me on twitter and leave a comment bellow! I’m always looking for friends online, and love to talk about mobile dev  and other cool stuff, so follow me already!

Download the .STL file:
(I suffered so you don’t have to)
iphone.stl

Create an iPhone stencil

First thing I did was download a picture of an iPhone 5s and open it in photoshop.
Screen Shot 2014-08-14 at 4.21.57 PMNext remove everything we don’t need in the image and save it as a png.
Screen Shot 2014-08-14 at 4.19.25 PM

Next I used a program called sketch up where can be downloaded here: http://www.sketchup.com/ . Open your png in sketch up and trace the entire image using the line and arch tools. This is the really lame part and takes forever. Once the image is outlined use the push/pull tool to give the selection thickness. Once you have something you like export it as an stl file and you are ready to print!

Screen Shot 2014-08-14 at 4.34.15 PMFinally open you .stl file in your perfered 3d printing program. I use Repetier with my Printerbot simple. Send the print job to your printer and that it! Unless you are terrible at configuring your printer and it takes like 20 print attempts to figure out why your printer isn’t doing what you want and you really start to wonder why you even bought the dang machine in the first place.

Screen Shot 2014-08-14 at 4.34.54 PM

So I couldn’t get my printer to work like I wanted to and modified the object to be only a couple of layers. It turned out pretty good. My PrintrBot simple only has a 100 mm x 100 mm x 100 mmx print area so the stencil isn’t actually to size but I am always writing my app ideas down in a note book I have and I actually like the smaller size to save space.

 

iOS Custom UIActionSheet

customActionSheetThe UIActionSheet is a great tool to easily let users select between multiple options. I use it all the time when developing apps. Just like all great and easy to use components, designers like to customize them and make developer’s lives harder than they have to be. In this tutorial I will show you how to make an action sheet that is easy to customize and allow you to control every aspect of its look and feel. If you would like to follow along the project is on git hub. Also before we get started, if you would like to follow me on twitter I am always looking for iOS developer friends!


Download this sample project on git hub

Quick! To the documentation

If you head over to Apple’s documentation we will quickly see that the UIActionSheet isn’t supposed to be subclassed.

UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy. If you need to present a sheet with more customization than provided by the UIActionSheet API, you can create your own and present it modally with presentViewController:animated:completion:.

So what will we do? We will create a UIView that looks and acts like an UIActionSheet. To get started lets create the class in Xcode. Select new objective-c class and name it CustomActionSheet and set it’s subclass to UIView. Next, lets also create a custom button that the action sheet will use. Select new objective-c class and name it ActionButton and make it a subclass of UIButton.

Action Button

Before we get started on the action sheet view lets finish up the button that the view will use. You don’t have to do this and could just insert a UIButton, but I like to subclass things like buttons because they will most likely be used all over the app. Here is what the ActionButton class looks like.

ActionButton.h

//
//  ActionButton.h
//  CustomUIActionSheet
//
//  Created by Barrett Breshears on 8/8/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

#import 

@interface ActionButton : UIButton

// class method that will be used when allocating button
+ (ActionButton *)buttonWithText:(NSString *)text cancel:(BOOL)cancel;

// instance method to set the button label and let the button know if it is a cancel button
- (id)initWithText:(NSString *)text cancel:(BOOL)cancel;

@property (nonatomic, retain) UILabel *label;

@end

ActionButton.m

//
//  ActionButton.m
//  CustomUIActionSheet
//
//  Created by Barrett Breshears on 8/8/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

#import "ActionButton.h"

@implementation ActionButton

+ (ActionButton *)buttonWithText:(NSString *)text cancel:(BOOL)cancel
{
    // return the initialized button
    return [[self alloc] initWithText:text cancel:(BOOL)cancel];
}

- (id)initWithText:(NSString *)text cancel:(BOOL)cancel
{
    // initialize
    self = [super init];
    if (self != nil) {
        
        // we are only using a single image for the demo, but this project is set up for
        // an image with a highlighted state
        UIImage *mainImage;
        UIImage *tappedImage;
        
        // check if the image is a cancel button, if it is  we will use a special image
        if (cancel) {
            mainImage = [UIImage imageNamed:@"red_button.png"];
            tappedImage = [UIImage imageNamed:@"red_button.png"];
        } else { // otherwise the default button image will be a green button
            mainImage = [UIImage imageNamed:@"green_button.png"];
            tappedImage = [UIImage imageNamed:@"green_button.png"];
        }
        
        // create the buttons frame based on the image size
        CGRect frame;
        frame.size = mainImage.size;
        self.frame = frame;
        
        // set button images
        [self setImage:mainImage forState:UIControlStateNormal];
        [self setImage:tappedImage forState:UIControlStateHighlighted];
        
        // set up button label
        _label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        _label.backgroundColor = [UIColor clearColor];
        _label.textColor = [UIColor whiteColor];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.text = text;
        [self addSubview:_label];
    }
    return self;
}

@end

As you can see, this is a simple button that will give us the look of both UIActionSheet buttons. This type of subclassing has always worked great for me and if I needed more variety I would change the cancel param to a button type with a string parameter with a switch or if statement to decide what image to use for the button.

CustomActionSheet Class

Now lets move on to the custom action sheet. We will create our view to behave just like an action sheet, initializing it with a title, button titles, and a cancel button title. It will also fire a custom delegate method to let the implementing object know the action sheet has been dismissed and a button was selected.

CustomActionSheet.h

The header file is nothing special, but has one little snippet of code that I always get excited to use which allows you to pass in as many strings as you need.

otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION

I always get excited when I get to use this. Anyway here is the CustomAction.h file.

//
//  CustomActionSheet.h
//  CustomUIActionSheet
//
//  Created by Barrett Breshears on 8/7/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

#import 

@class CustomActionSheet;

// define the custom actionview delegate
@protocol CustomActionViewDelegate 

@optional
// declare the option delegate method which passed in the alert and which button was selected
- (void)modalAlertPressed:(CustomActionSheet *)alert withButtonIndex:(NSInteger)buttonIndex;

@end

@interface CustomActionSheet : UIView

@property (assign) id  delegate;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, assign) float yPosition;
@property (nonatomic, assign) int index;

- (void)animateOn;
- (void)animateOff;
- (id)initWithTitle:(NSString *)title delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
- (void)buttonPressedWithIndex:(id)sender;
- (void)showAlert;

@end

CustomActionSheet.m

Here is a little overview of what we will be doing here:

–The view will need to be initialized and create the background, and all the buttons, adding and adjusting the views’ size depending on the number of buttons needed.

–Create an action method the buttons will use when they are clicked.

–We will need to create a showAlert method that adds the view to the window.

–Create methods to animate the view on and off the window.

Just a quick note I decided to call the delegate method [_delegate modalAlertPressed:self withButtonIndex:index] inside of the animateOff method instead of the – (void)buttonPressedWithIndex:(id)sender since there is a delay with animation. If you need to change this to fire immediately after the button is pressed you can stick it in the – (void)buttonPressedWithIndex:(id)sender method instead.

//
//  CustomActionSheet.m
//  CustomUIActionSheet
//
//  Created by Barrett Breshears on 8/7/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

#import "CustomActionSheet.h"
#import "ActionButton.h"

@interface CustomActionSheet ()

@end

@implementation CustomActionSheet
@synthesize backgroundView;
@synthesize yPosition;
@synthesize index;

- (id)initWithTitle:(NSString *)title delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
{
    self = [super init];
    if (self) {
        
        // set the delegate
        _delegate = delegate;
        
        // create a frame this will take up the full screen size
        self.frame = CGRectMake(0.0, 0.0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
        self.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.7];
        
        // set up the background view
        backgroundView = [[UIView alloc] init];
        backgroundView.backgroundColor = [UIColor colorWithRed:7.0/255.0f green:45.0/255.0f blue:58.0/255.0 alpha:1];
        backgroundView.userInteractionEnabled = YES;
        CGRect frame = backgroundView.frame;
        frame.size = CGSizeMake(320, 380);
        frame.origin = CGPointMake(0, self.frame.size.height);
        backgroundView.frame = frame;
        
        
        // get our button array from the otherButtonTittles parameter
        NSMutableArray *buttonArray = [[NSMutableArray alloc]init];
        va_list args;
        va_start(args, otherButtonTitles);
        for (NSString *arg = otherButtonTitles; arg != nil; arg = va_arg(args, NSString*))
        {
            [buttonArray addObject:arg];
        }
        va_end(args);
        
        
        // this will track the current position of where the elements will be placed
        yPosition = 15;
        
        // check if there is a title
        if (title != nil) {
            // create a the title and position it in the view
            UILabel *titleField = [[UILabel alloc] init];
            titleField.textColor = [UIColor whiteColor];
            titleField.shadowColor = [UIColor blackColor];
            [titleField setTextAlignment:NSTextAlignmentCenter];
            titleField.text = title;
            frame = titleField.frame;
            frame.size.width = self.frame.size.width ;
            frame.size.height = 19;
            frame.origin.x = self.frame.size.width/2 - frame.size.width/2;
            frame.origin.y = yPosition;
            titleField.frame = frame;
            [backgroundView addSubview:titleField];
            yPosition += titleField.frame.size.height + 10;
        }
        
        // i will be used to set the button's tag and is returned to delegate method
        int i;
        // loop through the buttons and create an ActionButton for each
        for (i = 0; i < buttonArray.count; i++) {
            ActionButton *alertButton = [ActionButton buttonWithText:[buttonArray objectAtIndex:i] cancel:NO];
            frame = alertButton.frame;
            frame.origin.x = backgroundView.frame.size.width/2 - frame.size.width/2;
            frame.origin.y = yPosition;
            alertButton.frame = frame;
            alertButton.tag = i;
            [alertButton addTarget:self action:@selector(buttonPressedWithIndex:) forControlEvents:UIControlEventTouchUpInside];
            [backgroundView addSubview:alertButton];
            yPosition += alertButton.frame.size.height + 10;
            
        }
        
        // increase the tag index for the cancel button
        i++;
        
        // create the cancel button
        ActionButton * cancel = [ActionButton buttonWithText:cancelButtonTitle cancel:YES];
        frame = cancel.frame;
        frame.origin.x = backgroundView.frame.size.width/2 - frame.size.width/2;
        frame.origin.y = yPosition;
        cancel.frame = frame;
        cancel.tag = i;
        [cancel addTarget:self action:@selector(buttonPressedWithIndex:) forControlEvents:UIControlEventTouchUpInside];
        [backgroundView addSubview:cancel];
        
        yPosition += cancel.frame.size.height + 15;
        
        frame = backgroundView.frame;
        frame.size.width = self.frame.size.width;
        frame.size.height = yPosition;
        backgroundView.frame = frame;
        
        // add the background view and animate the view on screen
        [self addSubview:backgroundView];
        [self animateOn];
        
        
    }
    return self;
}

// method that is fired when one of the ActionButtons is pressed
- (void)buttonPressedWithIndex:(id)sender
{
    // get the button that was pressed
    ActionButton *button = (ActionButton *)sender;
    index = (int)button.tag;
    [self animateOff];
}


// shows the action sheet by adding it to the key window
- (void)showAlert
{
    [[[UIApplication sharedApplication]keyWindow]addSubview:self];
}


// animate the view on to the screen
- (void)animateOn
{
    [UIView animateWithDuration:.23 animations:^{
        
        CGRect frame = backgroundView.frame;
        frame.origin.y -= yPosition;
        backgroundView.frame = frame;
        
    }];
}

// remove the view with animation once removed the delegate method is fired off notifying the
// object that implemented the CustomActionSheet
- (void)animateOff
{
    [UIView animateWithDuration:.23 animations:^{
        
        CGRect frame = backgroundView.frame;
        frame.origin.y += yPosition;
        backgroundView.frame = frame;
        
    } completion:^(BOOL complete){
        [_delegate modalAlertPressed:self withButtonIndex:index];
        [self removeFromSuperview];
    }];
}
@end

This is a really basic example and hopefully will be a great starting point if you ever needed a custom designed UIActionSheet. Let me know if you have any questions or comments in the comment section below, I would love to hear from you! Also if you ever want to talk about iOS or any kind of development send me a message on twitter. Thanks for reading!

UIView Animations with Objective C for iOS

When developing an app, animations can make the defierence between a good user experience and a great one. Like most things in programing there are serveral ways to animate ui components, but I will be using the UIView class with block-based animation methods. This works with iOS 4 and greater.

UIView animateWithDuration: and block-based animation methods

There are 3 main methods that I use but there are a couple others:

[UIView animateWithDuration:0.2
                 animations:^{
       // animations go here
}];


[UIView animateWithDuration:0.2
                 animations:^{
                     // animations go here
                 }
                completion:^(BOOL finished) {
                    // block fires when animation has finished
}];


[UIView animateKeyframesWithDuration:0.2
                               delay:0.0
                             options:UIViewKeyframeAnimationOptionCalculationModeLinear
                          animations:^{
                              // animations go here
                          }
                          completion:^(BOOL finished) {
                              // block fires when animaiton has finished
}];

You can take a look at the UIView Class Reference for all the animation methods as well as other techniques for animation.

Lets animate something!

Now that we know what methods to use lets try and animate something. In this example we are animate two views to the left and then back to their original position. There will be 2 buttons to allow you to set the animation options (to view all the available options take a look at the UIView Class Reference), and allow you to see the difference between the two. You can also grab the project on github and follow along.

Setting up the storyboard and .h file

To start we are going to set up the view in the storyboard by creating the IBOutlets and hooking them up in interface builder.

//
//  ViewController.h
//  objectiveCAnimation
//
//  Created by Barrett Breshears on 6/29/14.
//  Copyright (c) 2014 Barrett Breshears. All rights reserved.
//

#import 

@interface ViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIButton *animationOption1;
@property (nonatomic, strong) IBOutlet UIButton *animationOption2;
@property (nonatomic, strong) IBOutlet UIButton *animateBtn;
@property (nonatomic, strong) IBOutlet UIButton *pickerSelectBtn;


@property (nonatomic, strong) IBOutlet UIView *view1;
@property (nonatomic, strong) IBOutlet UIView *view2;

@property (nonatomic, strong) IBOutlet UIPickerView *animationPicker;

@property (nonatomic, assign) UIViewAnimationOptions animation1;
@property (nonatomic, assign) UIViewAnimationOptions animation2;

@property (nonatomic, strong) NSArray *animationNames;

@property (nonatomic, assign) BOOL animationInProgress;

-(IBAction)selectAnimation1:(id)sender;
-(IBAction)selectAnimation2:(id)sender;
-(IBAction)animateViews:(id)sender;

@end

Interface Builder

Animating the views

Animating the views will be super easy. We will be animating the views frame, but you can change this to anything you want (like scale: _view1.transform = CGAffineTransformMakeScale(1.0, 1.0); ), and you can have as many animations as you want in there. Also you will notice that we have a nested animation inside the completion block that animates the view back to the original position.

  // animation 1
    [UIView animateKeyframesWithDuration:0.5
                                   delay:0.0
                                 options:_animation1
                              animations:^{
                                _view1.frame = CGRectMake(_view1.frame.origin.x + 200, _view1.frame.origin.y, _view1.frame.size.width, _view1.frame.size.height);
                              }
                              completion:^(BOOL finished) {
                                  [UIView animateKeyframesWithDuration:0.5
                                                                 delay:0.0
                                                               options:_animation1
                                                            animations:^{
                                                                _view1.frame = CGRectMake(_view1.frame.origin.x - 200, _view1.frame.origin.y, _view1.frame.size.width, _view1.frame.size.height);
                                                            }
                                                            completion:^(BOOL finished) {
                                                                _animationInProgress = NO;
                                                            }];
                              }];
    // animation 2
    [UIView animateKeyframesWithDuration:0.5
                                   delay:0.0
                                 options:_animation2
                              animations:^{
                                  _view2.frame = CGRectMake(_view2.frame.origin.x + 200, _view2.frame.origin.y, _view2.frame.size.width, _view2.frame.size.height);
                              }
                              completion:^(BOOL finished) {
                                  [UIView animateKeyframesWithDuration:0.5
                                                                 delay:0.0
                                                               options:_animation2
                                                            animations:^{
                                                                _view2.frame = CGRectMake(_view2.frame.origin.x - 200, _view2.frame.origin.y, _view2.frame.size.width, _view2.frame.size.height);
                                                            }
                                                            completion:^(BOOL finished) {
                                                                _animationInProgress = NO;
                                                            }];
                              }];

animation
This is a very basic example but it shows how easy adding animation to your views are. If you have any questions please let me know in the comment or sent me messages on twitter @barrettbreshears. Also if this post helped you out I would appreciate if you share with your friends on twitter! Thanks for reading!

Singleton Objective C | iOS

There are times when developing an application I need to have a single instance of a class. For example recently I needed to build an audio player that managed a song queue, and if the queue was playing. I also needed to be able to modify the queue from another view controller, so it was the perfect time to utilize the singleton pattern.

Singleton Pattern

In my example I am creating a singleton using an NSObject, this basic principle can be used on an type object. So lets take a look at the header file:

//
//  MySingleton.h
//
//  Created by Barrett A Breshears 
//

#import 

@interface MySingleton : NSObject

@property (nonatomic, retain) NSString *singletonValue;

+(MySingleton *)sharedMySingleton;

@end

Its a simple header file with a single NSString property and class method declaration. Now lets take a look at the implementation file.

//
//  MySingleton.m
//
//  Created by Barrett A Breshears
//

#import "MySingleton.h"

@implementation MySingleton

static MySingleton *_sharedMySingleton = nil;

+(MySingleton*)sharedMySingleton{
    @synchronized([MySingleton class]) {
        if (!_sharedMySingleton){
            _sharedMySingleton = [[self alloc] init];
        }
        return _sharedMySingleton;
    }
    return nil;
}

+(id)alloc {
    @synchronized([MySingleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Singleton already initialized.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }
    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }   return self;
}
@end

First I declare a static instance of the MySingleton Class. Next I write my class method which checks to see if there is an instance of the singleton already created. If there isn’t it goes ahead and alloc and inits itself:

+(MySingleton*)sharedMySingleton{
    @synchronized([MySingleton class]) {
        if (!_sharedMySingleton){
            _sharedMySingleton = [[self alloc] init];
        }
        return _sharedMySingleton;
    }
    return nil;
}

You will notice that I’m using @synchronized inside of all the methods related to referencing allocating and initializing the singleton. Apple’s docs on threading are great. Take some time to read them if you want to learn more about threading and sycronization, but here is a sinpit that is important to what we are working on:

The presence of multiple threads in an application opens up potential issues regarding safe access to resources from multiple threads of execution. Two threads modifying the same resource might interfere with each other in unintended ways. For example, one thread might overwrite another’s changes or put the application into an unknown and potentially invalid state. If you are lucky, the corrupted resource might cause obvious performance problems or crashes that are relatively easy to track down and fix. If you are unlucky, however, the corruption may cause subtle errors that do not manifest themselves until much later, or the errors might require a significant overhaul of your underlying coding assumptions.

When it comes to thread safety, a good design is the best protection you have. Avoiding shared resources and minimizing the interactions between your threads makes it less likely for those threads to interfere with each other. A completely interference-free design is not always possible, however. In cases where your threads must interact, you need to use synchronization tools to ensure that when they interact, they do so safely.

So the @synchronized directive is an easy way to allow us to lock the object so it can’t be corrupted by multiple threads.

Next I set up my alloc class method and init instance method, again using @synchronized directive to lock the object.

+(id)alloc {
    @synchronized([MySingleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Singleton already initialized.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }
    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }   return self;
}

And that’s it. We can use the MySingleton class like this:

[MySingleton sharedMySingleton].singletonValue = @"Sledge Dev";

Using Singletons

The singleton is first pattern I learned when I start object oriented programming a long time ago. I really like it, and am probably guilty of overusing it myself. I have read a lot about how it not such a great idea to use a singleton, there are a ton of great articles out there if you want more info about this subject. Here are a couple of my favorites:

Personally I think there is a time and a place to use them, but please let me know what you think in the comments down below.