Come Write Software

October 16th, 2009

Come write software with me and the rest of Raizlabs. We’re looking to build our team of developers. Are you interested in writing mobile applications? Send me a note.

Objective-C SHA1 Function for the iPhone

September 25th, 2009

Here’s a nice little function that will generate an SHA-1 hash digest that will match what the php sha1() function will generate if you give it the same input:

#import

@implementation SHA1

+(NSString*) digest:(NSString*)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];

uint8_t digest[CC_SHA1_DIGEST_LENGTH];

CC_SHA1(data.bytes, data.length, digest);

NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];

return output;

}


@end

Drawing polyines or routes on a MKMapView (as an MKAnnotationView) – Part 2

August 19th, 2009

It turns out there is a better way to display routes on a map than the last example I gave. The problem with my last example is that the route exists in a layer above the map view, resulting in the line of the route being drawn on top of any annotation views. So pins, photos and anything else expressed as an MKAnnotation would be drawn over by the routes in the layer above the map view.

The solution to this problem then is to draw the lines as usual, but in a custom MKAnnoationView. This view will be set to not clip its own subviews, and will then have a subview that lies outside the frame of the annotation view, and this subview will draw the lines. The route annotation view needs a subview to do the rendering which will always be positioned at the full frame size and origin of the map. This way the MKAnnotationView can be smaller than the route, but it  always draws in the internal subview, which is the size of the map view.

So… long story short: the ability to put a route on a MKMapView via a custom MKAnnotation. You can download the sample code here.

//
// CSRouteView.m
// testMapp
//
// Created by Craig on 8/18/09.
// Copyright Craig Spitzkoff 2009. All rights reserved.
//
#import "CSRouteView.h"
#import "CSRouteAnnotation.h"
// this is an internally used view to CSRouteView. The CSRouteView needs a subview that does not get clipped to always
// be positioned at the full frame size and origin of the map. This way the view can be smaller than the route, but it
// always draws in the internal subview, which is the size of the map view.
@interface CSRouteViewInternal : UIView
{
// route view which added this as a subview.
CSRouteView* _routeView;
}
@property (nonatomic, retain) CSRouteView* routeView;
@end
@implementation CSRouteViewInternal
@synthesize routeView = _routeView;
-(void) drawRect:(CGRect) rect
{
CSRouteAnnotation* routeAnnotation = (CSRouteAnnotation*)self.routeView.annotation;

// only draw our lines if we're not int he moddie of a transition and we
// acutally have some points to draw.
if(!self.hidden && nil != routeAnnotation.points && routeAnnotation.points.count > 0)
{
CGContextRef context = UIGraphicsGetCurrentContext();

if(nil == routeAnnotation.lineColor)
routeAnnotation.lineColor = [UIColor blueColor]; // setting the property instead of the member variable will automatically reatin it.

CGContextSetStrokeColorWithColor(context, routeAnnotation.lineColor.CGColor);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);

// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 2.0);

for(int idx = 0; idx < routeAnnotation.points.count; idx++)
{
CLLocation* location = [routeAnnotation.points objectAtIndex:idx];
CGPoint point = [self.routeView.mapView convertCoordinate:location.coordinate toPointToView:self];

NSLog(@"Point: %lf, %lf", point.x, point.y);

if(idx == 0)
{
// move to the first point
CGContextMoveToPoint(context, point.x, point.y);
}
else
{
CGContextAddLineToPoint(context, point.x, point.y);
}
}

CGContextStrokePath(context);

// debug. Draw the line around our view.
/*
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, 0, self.frame.size.height);
CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height);
CGContextAddLineToPoint(context, self.frame.size.width, 0);
CGContextAddLineToPoint(context, 0, 0);
CGContextStrokePath(context);
*/
}

}
-(id) init
{
self = [super init];
self.backgroundColor = [UIColor clearColor];
self.clipsToBounds = NO;

return self;
}
-(void) dealloc
{
self.routeView = nil;

[super dealloc];
}
@end
@implementation CSRouteView
@synthesize mapView = _mapView;
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor clearColor];
// do not clip the bounds. We need the CSRouteViewInternal to be able to render the route, regardless of where the
// actual annotation view is displayed.
self.clipsToBounds = NO;

// create the internal route view that does the rendering of the route.
_internalRouteView = [[CSRouteViewInternal alloc] init];
_internalRouteView.routeView = self;

[self addSubview:_internalRouteView];
}
return self;
}
-(void) setMapView:(MKMapView*) mapView
{
[_mapView release];
_mapView = [mapView retain];

[self regionChanged];
}
-(void) regionChanged
{
NSLog(@"Region Changed");

// move the internal route view.
CGPoint origin = CGPointMake(0, 0);
origin = [_mapView convertPoint:origin toView:self];

_internalRouteView.frame = CGRectMake(origin.x, origin.y, _mapView.frame.size.width, _mapView.frame.size.height);
[_internalRouteView setNeedsDisplay];

}
- (void)dealloc
{
[_mapView release];
[_internalRouteView release];

[super dealloc];
}
@end

Lumbar Epidural Steroid Injection

June 19th, 2009

Today I had a series injections of anesthetics and steroids in my spine. These are supposed to temporarily relieve my pain over the next two or three weeks. After that, we get to see if I am still in pain, and how bad it is, and that will be the lead determining factor of whether I go in for a discectomy to take care of the herniated disc. The discectomy would be a minimally invasive micro endoscopic procedure, which depending on the results may or may not be an outpatient procedure.

The shots I had today were painless, and the radiologist who administered them was amazing. The hard part though was lying on my stomach long enough to receive the injections. This three minutes of lying on my stomach was probably one of the most painful experiences of my life. My back just can not support that position right now. But relief came quickly afterward, so the three minutes of extreme pain was worth it.

What I’m hoping for, of course, is that after three weeks and the wearing off of the steroid injection, that the ejected disc material pushing up against my sciatic nerve will have been reabsorbed or receded away from my nerves. That’s really the source of all this pain; not the rupturing of the disc, but rather the pressing on and displacement of my lumbar nerves. If I’m not in pain after that, I can start some more serious physical therapy and hopefully get some strength back. But the radiologists reaction to my MRI was not encouraging, and he gave the impression that any relief he could offer would only be temporary. Only time will tell.

New England Baptist Hospital was impressive though. No smoking anywhere on their campus, super clean and modern, all the support staff were in suits… it just felt like a very well run operation.

In light of all this JobVent.com prospecting goes well… I’ve had several good conversations over the last few days. The power of online social networking in situations like this is becoming extremely clear. LinkedIn and Twitter have been indispensable.

Ouch

June 15th, 2009

My Herniated Disc
I’m trying to sell JobVent.com. Here’s why.

About a week ago, I had an MRI, which revealed a 19.4mm herniation in the disc between my L4 and L5 vertebrae. What happens when you have a disc herniation is that the outer casing of the disc ruptures, and the gel within the disc is forced out. In some cases, the herniation is bad enough that it puts a great deal of pressure on the nerves that run through the back of the spine. This is currently what is happening to me.

Walking is now difficult, sitting in a chair even more so. And we software developers, well, we like to sit in chairs. I’m comfortable when standing, but only after standing for about 10 minutes.

It seems more and more likely that I will be having spinal surgery to address this problem. We’ll find out after I talk to several surgeons.

After the family tragedy we went through this winter, and the pain I am going through right now, its becoming more and more difficult for me to find energy and time to maintain JobVent.com. I find myself with several new main focuses in my life, and these are as follows:

  1. Recover. Be it through surgery or physical therapy or a combination of the two, I simply cannot function while in this much pain. My main goal right now is the restoration of my own physical health.
  2. Family. We had a very tough winter, but we go on. My wife is my world. We will have children.
  3. Work. I write great software, and my main focus is mobile development. I enjoy it, I work with an amazing team, and we’re going to continue building amazing products for multiple platforms.

Unfortunately, as you see, JobVent.com does not make the list. So if you, or someone you know is interested in acquiring what turns out to be a fairly popular website, please, send me an email. I’ll answer any questions you have.

Using MKAnnotation, MKPinAnnotationView and creating a custom MKAnnotationView in an MKMapView

May 16th, 2009

My last experiment maps on the iPhone using the MKMapView from the iPhone’s MapKit was an example of how to use the MKMapView to display the line of a route on the map.

Today’s experiment will demonstrate how to drop pin annotation views, as well as custom annotation views on the iphone’s map by providing the map with objects that implement the MKAnnotation protocol.

The class I created that implements MKAnnotation can be used to differentiate between those annotations that should be represented by MKPinAnnotationViews of diferernt colors, as well as our custom annotation view, CSImageAnnotationView. The CSMapAnnotation class needs to keep track of additional information such as images and URLs that can be used for a custom display.

This is the header for the custom annotation. You can see that there is an enumeration that is used to designate what type of annotation view should be used for display of each annotation on the iPhone’s map. Also available are the userData and url properties; userData can be used to store anything, but in the case of this example, we’re using it to store path information for an image that should be displayed on the map. Title is also an available property, but subtitle will be generated on the fly.

//
// CSMapAnnotation.h
// mapLines
//
// Created by Craig on 5/15/09.
// Copyright 2009 Craig Spitzkoff. All rights reserved.
//

#import
#import

// types of annotations for which we will provide annotation views.
typedef enum {
CSMapAnnotationTypeStart = 0,
CSMapAnnotationTypeEnd = 1,
CSMapAnnotationTypeImage = 2
} CSMapAnnotationType;

@interface CSMapAnnotation : NSObject
{
CLLocationCoordinate2D _coordinate;
CSMapAnnotationType _annotationType;
NSString* _title;
NSString* _subtitle;
NSString* _userData;
NSURL* _url;
}

-(id) initWithCoordinate:(CLLocationCoordinate2D)coordinate
annotationType:(CSMapAnnotationType) annotationType
title:(NSString*)title;

@property CSMapAnnotationType annotationType;
@property (nonatomic, retain) NSString* userData;
@property (nonatomic, retain) NSURL* url;

@end

In most cases, when our MKMapViewDelegate is asked for an MKAnnotation, we return a MKPinAnnotation. If the CSMapAnnotation is set to be CSMapAnnotationTypeImage , the delegate instead produces an instance of our custom annotation view, CSImageAnnotationView, and sets its properties based on the annotation’s user data.

This is the body of our custom annotation view. It is pretty simple; the bulk of the functionality is in the initialization function, which sets up the view to have a UIImageView.

//
// CSImageAnnotationView.m
// mapLines
//
// Created by Craig on 5/15/09.
// Copyright 2009 Craig Spitzkoff. All rights reserved.
//

#import "CSImageAnnotationView.h"
#import "CSMapAnnotation.h"

#define kHeight 100
#define kWidth 100
#define kBorder 2

@implementation CSImageAnnotationView
@synthesize imageView = _imageView;

- (id)initWithAnnotation:(id )annotation reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
self.frame = CGRectMake(0, 0, kWidth, kHeight);
self.backgroundColor = [UIColor whiteColor];

CSMapAnnotation* csAnnotation = (CSMapAnnotation*)annotation;

UIImage* image = [UIImage imageNamed:csAnnotation.userData];
_imageView = [[UIImageView alloc] initWithImage:image];

_imageView.frame = CGRectMake(kBorder, kBorder, kWidth - 2 * kBorder, kWidth - 2 * kBorder);
[self addSubview:_imageView];

return self;

}

-(void) dealloc
{
[_imageView release];
[super dealloc];
}

@end

So, how does the map know to ask the delegate for annotation views? It knows to do this based on annotations that are added to the map in our view controller’s viewDidLoad method.


// create the image annotation
annotation = [[[CSMapAnnotation alloc] initWithCoordinate:[[points objectAtIndex:points.count / 2] coordinate]
annotationType:CSMapAnnotationTypeImage
title:@"Cleveland Circle"] autorelease];
[annotation setUserData:@"cc.jpg"];
[annotation setUrl:[NSURL URLWithString:@"http://en.m.wikipedia.org/wiki/Cleveland_Circle"]];

[_mapView addAnnotation:annotation];

UPDATE – 6/1/2009
You’ll notice we set the URL on the annotation above, and the code has now been updated to display that webpage when the user clicks the annotation disclosure of our custom image annotation view. The code sample you can download has been updated to reflect this change.

The full code of this example is available for download here.

Update – 8/19/2009
Another update. This one displays the route as an annotation view, so it does not render on top of other annotations.You can view the update at this link.

RemoteIO Audio Unit for FFT based on compressed stream output

May 6th, 2009

Today, I pose a question for other iPhone developers who have a lot of experience working with Audio.

The examples I have seen out there performing FFTs on audio have all been based around the same concept from the aurioTouch example code. This code works well for me, however I would like to perform the FFT analysis on the outgoing audio from a compressed file stream, instead of input from the microphone. Now I have the file stream working as output via audio queues, as well as the RemoteIO Audio Unit receiving data from the mic at the same time, but I’d much rather the audio buffers being sent to my audio unit’s AURenderCallback be representative of the data being played back, instead of the data being received from the microphone.

So, I guess my question is this: Can I set up a RemoteIO Audio Unit to intercept outgoing uncompressed audio buffers based on compressed audio being played back through audio queues?

Thanks in advance… first applicable code snippet gets a prize.

Drawing polyines or routes on a MKMapView (Using Map Kit on the iPhone)

April 12th, 2009

Apple recently released the 3.0 Beta of their iPhone SDK. One of the most exciting new items in this SDK for me was the addition of the MapKit framework. This new mapping component would allow developers to add maps to their applications that have similar performance and functionality to the Google Maps application that ships with the iPhone.

Unfortunately, there are a few useful pieces missing from the new map SDK; the most glaring of which (to me) is the built in ability to draw routes on a map. This is easily solved though by placing a custom UIView over the map that acts as the map delegate, and knows how to take a series of CLLocation coordinates and plot them on the map, regardless of the location the user pans to or how far they have zoomed in.

I have included the code of this custom class below, as well as some tips on how to use it. There are two things to keep in mind though when looking at this code:

  1. It is in no way optimized, meaning the bulk of the drawRect functionality executes, regardless if the polyline being rendered is completely off screen.
  2. The Map Kit SDK is still in Beta, and is subject to change. This sample was written targeting the second beta of the 3.0 iPhone SDK. I do not anticipate huge changes in the SDK, but future releases may break the code listed below, or (hopefully) make the code below completely uneccessary.

Going through the code, you can see when this new CSMapRouteLayerView is initialized with an array of CLLocations and a MapView, the view adds itself as the subview to the MKMapView and registers as its delegate. It then, based on the points that were passed in, uses the map to determine the region that would result in the full path of the route’s line being displayed. The map is then zoomed to this region that contains the while route.

The drawRect functionality is pretty straightforward; for every geographic point in the array, it uses the map to determine the pixel coordinates of that point, and then draws a line to that point from the previous point (in the case of the first point, it just moves the pen to that location and nothing is drawn till the next point).

One downside to this approach, and you can see this in the MKMapViewDelegate handlers in the route layer view, is that when the user decides to scroll or zoom the map, we must temporarily disable the display of the route. This is because during the transition, the lines will appear to be rendered at the wrong location. As soon as the region is done changing, we can bring our polyline back onto the map.

The sample data used for this project is a CSV file with some Latitude/Longitude pairs. The applications main view controller does the work of opening up this file, parsing out the points, and sending it to the initialization of our route layer view. I have not copied the code for this below, but you can see it if you download the sample project.

I have an updated post here that builds on this project and also discusses using Using MKAnnotation, MKPinAnnotationView and creating a custom MKAnnotationView in an MKMapView.

8-19-2009: Another update. This one displays the route as an annotation view, so it does not render on top of other annotations. You can view the update at this link.

Here’s the important code… you can download the sample project here: mapLines Sample Project

//
// CSMapRouteLayerView.h
// mapLines
#import
#import

@interface CSMapRouteLayerView : UIView
{
MKMapView* _mapView;
NSArray* _points;
UIColor* _lineColor;
}

-(id) initWithRoute:(NSArray*)routePoints mapView:(MKMapView*)mapView;

@property (nonatomic, retain) NSArray* points;
@property (nonatomic, retain) MKMapView* mapView;
@property (nonatomic, retain) UIColor* lineColor;

@end

//
// CSMapRouteLayerView.m
// mapLines
#import "CSMapRouteLayerView.h"

@implementation CSMapRouteLayerView
@synthesize mapView = _mapView;
@synthesize points = _points;
@synthesize lineColor = _lineColor;

-(id) initWithRoute:(NSArray*)routePoints mapView:(MKMapView*)mapView
{
self = [super initWithFrame:CGRectMake(0, 0, mapView.frame.size.width, mapView.frame.size.height)];
[self setBackgroundColor:[UIColor clearColor]];

[self setMapView:mapView];
[self setPoints:routePoints];

// determine the extents of the trip points that were passed in, and zoom in to that area.
CLLocationDegrees maxLat = -90;
CLLocationDegrees maxLon = -180;
CLLocationDegrees minLat = 90;
CLLocationDegrees minLon = 180;

for(int idx = 0; idx < self.points.count; idx++)
{
CLLocation* currentLocation = [self.points objectAtIndex:idx];
if(currentLocation.coordinate.latitude > maxLat)
maxLat = currentLocation.coordinate.latitude;
if(currentLocation.coordinate.latitude < minLat)
minLat = currentLocation.coordinate.latitude;
if(currentLocation.coordinate.longitude > maxLon)
maxLon = currentLocation.coordinate.longitude;
if(currentLocation.coordinate.longitude < minLon)
minLon = currentLocation.coordinate.longitude;
}

MKCoordinateRegion region;
region.center.latitude = (maxLat + minLat) / 2;
region.center.longitude = (maxLon + minLon) / 2;
region.span.latitudeDelta = maxLat - minLat;
region.span.longitudeDelta = maxLon - minLon;

[self.mapView setRegion:region];
[self.mapView setDelegate:self];
[self.mapView addSubview:self];

return self;
}

- (void)drawRect:(CGRect)rect
{
// only draw our lines if we're not int he moddie of a transition and we
// acutally have some points to draw.
if(!self.hidden && nil != self.points && self.points.count > 0)
{
CGContextRef context = UIGraphicsGetCurrentContext();

if(nil == self.lineColor)
self.lineColor = [UIColor blueColor];

CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);

// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 2.0);

for(int idx = 0; idx < self.points.count; idx++)
{
CLLocation* location = [self.points objectAtIndex:idx];
CGPoint point = [_mapView convertCoordinate:location.coordinate toPointToView:self];

if(idx == 0)
{
// move to the first point
CGContextMoveToPoint(context, point.x, point.y);
}
else
{
CGContextAddLineToPoint(context, point.x, point.y);
}
}

CGContextStrokePath(context);
}
}

#pragma mark mapView delegate functions
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
// turn off the view of the route as the map is chaning regions. This prevents
// the line from being displayed at an incorrect positoin on the map during the
// transition.
self.hidden = YES;
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
// re-enable and re-poosition the route display.
self.hidden = NO;
[self setNeedsDisplay];
}

-(void) dealloc
{
[_points release];
[_mapView release];
[super dealloc];
}

@end

Interview Question

April 7th, 2009

I just read an interesting article about a well known marketing executive in NYC. One specific part of the article talks about how horrible he was to work for; the example given is that he would make employees do push-ups in front of clients (the reason for which is not provided).

This got me thinking about a story I heard once about an interesting question encountered at a job interview. The question was “What would be your response if I asked you to do some push-ups?” The job being interviewed for was something software related, development or testing; I forget. The nature of the job is unimportant except for the fact that there are not any physical requirements for the job, other than being able to show up at the office and operate a computer.

The answer that landed the job? “I’d ask you why you want me to do push-ups.”

From what I understand, the employer in question would not hire anyone that upon hearing the question decided to get down on the floor and do push-ups. Nor would they hire anyone who asked “How many would you like?” or any variation thereof. Many candidates when asked this question immediately got defensive, telling the interviewer it was inappropriate for them to ask for push-ups at any time, especially during a job interview. These candidates were also not considered for the job.

What most candidates for this particular company forgot to do was listen to the question. No one was asked to do push-ups. A question was asked about a hypothetical scenario in which an interviewee would be asked to perform a physical activity. The ideal candidate would know there is something wrong with an interviewer asking someone to do push-ups, but would be inquisitive and open-minded enough to inquire as to “why” push-ups would be requested before making their decision. Those candidates that immediately became defensive of their right not to have to do push-ups are not considering that there may be, even though they are unaware of the possibilities, a valid reason for such an odd request. It represents a closed-mindedness that the company was trying to avoid having in their employees. Candidates who immediately decided to do push-ups or ask for details about the push-ups they were about to do, while obviously eager to work for the company and willing to sacrifice, did not listen to the question, and lack the important instinct to question authority.

So, remember its OK to ask “why” during a job interview. But if an interviewer actually asks you to do push-ups, ask yourself if you’re OK with that level of disrespect.

JobVent.com in the Columbus Dispatch

December 7th, 2008

A big thank-you to Steve Wartenberg for his article entitled Cyber Venting. Steve, and the experts he cites make the point that comments on sites such as JobVent.com should be strongly considered by executives and managers within the organizations about which people are writing. They also urge people who read these sites to take the comments they read with “a grain of salt” due to the fact that you do not really know who is writing these reviews and whether their opinions should actually sway your opinion about a company.

I see examples of this a lot on JobVent.com. Someone gets fired from a job, and decides to write an extremely negative review. They have every right to express their opinion, but people reading the review really should consider the context in which this person was motivated to write it. Why were they fired? Unless the company or other people within the organization decide to respond to this review, readers of the recently terminated employee’s review will only be reading half of the story, and they need to keep that in mind. We have no idea if the employee was not performing their job well enough to justify their continued employment, or if there were any number of unmentioned issues that the other side could have had with this employee.

Always consider both sides of the story, even when you’ve only been handed one of them.