iPad Programming Tutorial – Hello World++

iPad Programming Tutorial – Hello World++

Introduction

Now, that the iPad has been released, I’m sure you are all scrambling for ideas on how to snag a piece of the maket in the imminent gold rush.  iCodeBlog is going to help you on your journey with a series of iPad tutorials to come.

Since the iPad uses the same SDK as the iPhone, all of the code under the hood is almost identical.  Actually, when looking at the new and changed API classes, you will realize that most of them are user interface related.  This is good news for us since we have already been coding iPhone.

While this tutorial is called “Hello World”, it is really much more than that.  I assume you already have working knowledge of iPhone/Objective-C programming.

What We Will Be Creating

In today’s tutorial, I will be showing you how to create an iPad project that uses the UISplitViewController to display content in 2 separate panes.  We will also be touching on some of the new design/UI patterns and giving an overall introduction to iPad programming.

The project will be based on one of my earliest tutorials that displayed a list of fruit in a UITableView and drilled down when they were selected.  We will be expanding on that example and creating something that will look like this.

It uses a UISplitViewController to display a UITableView on the left and a UIView with a UIImageView subview on the right.  This project is actually quite simple to create as the template code provides much of the code we need to get started.

Getting Started

1. Make sure you have downloaded the 3.2 SDK form http://developer.apple.com/ipad/.  The iPad simulator will come with this download.

2. Download the resources needed for this project and unzip them iPadHelloWorldResources.zip . (contains image files and a plist we will be using to load the images)

Creating The Project

Starting a project for the iPad is no different than starting one for the iPhone.  When you open XCode and select File->New Project, you should notice the addition of a Split View-Based Application.  Select this and name it iPadHelloWorld.

This will create a basic application with a UITableView on the left and a UIView on the right.  It will even populate the table with some sample elements.  It will add the following files to your project.

Here is a brief description of each of these files:

  • iPadHelloWorldAppDelegate – This is similar to every app delegate.  If you look in the application:didFinishLaunchingWithOptions method, you will see that the UISplitViewController is being allocated with the MasterViewController and DetailViewControllers.
  • MasterViewController – A UITableViewController, nothing fancy.  It will be handling the view on the left hand side.
  • DetailViewController – This handles the content view that you see on the right hand side.  We will be updating this as the user selects different rows in the table to the left.  This simply houses a single view.

Go ahead and press Build and Run to check out the application.  If you haven’t already done so, play around with the iPad contacts and settings apps as well.

Note: When you launch the application, you will only see the main view since the simulator runs in vertical mode.  To see the views side-by-side, rotate the simulator by clicking “Hardware -> Rotate Left/Right”.  You can also press CMD->Arrow Left/Right on the keyboard.

Importing The Project Images

Once you have had some time to play with the new iPad project, you will now need to import the images needed for this project.  After downloading and unzipping the files in from this tutorial, drag them into the project folder called “Resources-iPad”.

XCode will prompt you to copy the files, check yes and click OK.

Make sure you include all 4 images files as well as the file named fruits.plist.

Displaying The List Of Fruits

Displaying our fruits list is no different than displaying data in any other UITableView.  Let’s begin by opening MasterViewController.h and adding a declaration for our fruits array.

#import 
 
@class DetailViewController;
 
@interface MasterViewController : UITableViewController {
    DetailViewController *detailViewController;
    NSArray * fruits;
}
 
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@property (nonatomic, retain) NSMutableArray *fruits;
 
@end

As you can see, there is nothing new here.  We simply declare our fruits array and create a property for it.

We will be loading the fruits from the plist file that you imported into your project in the last step.  Loading content from a plist file is a very quick and easy solution when you don’t require a database.

Open up MasterViewController.m and add the following line of code to your viewDidLoad method.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fruits = [[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"fruits" ofType:@"plist"]] retain];
}

The file fruits.plist is essentially an array that has been written out to a file.  If you open it up, it looks very similar to XML.  Now that our fruits array has been populated, let’s implement each of the UITableView delegate and datasource methods to populate the table.

UITableView datasource methods

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [fruits count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"CellIdentifier";
 
	// Dequeue or create a cell of the appropriate type.
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
 
    // Get the object to display and set the value in the cell.
    cell.textLabel.text = [self.fruits objectAtIndex:indexPath.row];
    return cell;
}

Nothing special… We first tell the tableview that we want fruits.count (4 in this case) number of rows.

Next, we display the name of the fruit in each tableview cell.  If you want to learn more on UITableViews, read this tutorial.

UITableView delegate methods

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
    /*
     When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
     */
    detailViewController.detailItem = [self.fruits objectAtIndex: indexPath.row];
}

Here, we are simply setting the detailItem property of the detailViewController to the selected fruit.  We will discuss this property later in this section, but for now all you need to know is that its type is id.

At this point, go ahead and press Build and Run to see your code in action.  You should see something that looks like this:

It displays the list of fruits, but nothing happens when you select a cell (well the title of the detailView may change).

Now that we have our list of fruits displayed, we now need to implement the code to display their corresponding image.

Displaying The Fruits

Displaying the selected fruit is actually quite simple.  The first thing we need to do is add a UIImageView to our detailView.

Start by adding the IBOutlet for the image view.  Open up DetailViewController.h and add the following code:

@interface DetailViewController : UIViewController  {
 
    UIPopoverController *popoverController;
    UINavigationBar *navigationBar;
 
    id detailItem;
 
    IBOutlet UIImageView * fruitImageView;
}
 
@property (nonatomic, retain) UIPopoverController *popoverController;
@property (nonatomic, retain) IBOutlet UINavigationBar *navigationBar;
 
@property (nonatomic, retain) id detailItem;
 
@property (nonatomic, retain) IBOutlet UIImageView * fruitImageView;
 
@end

All of the code here comes with the template except the code to add the IBOutlet UIImageView.  Once you have added this open up DetailView.xib in interface builder.

Add a UIImageView on to the view and size it to 500×500.

Now, click on the File’s Owner object and open the connection inspector (Tools -> connection inspector).

Drag from your imageView IBOutlet to the UIImageView and release.  The UIImageView is now connected to your outlet.

Note: If you want the images to not skew, set the content mode of the image view (in the attributes inspector) to Aspect Fit.

Now that the imageview has been connected, it’s time to write the code that updates it.  Close Interface Builder and open the file DetailViewController.m and add the following lines to the setDetailItem method:

- (void)setDetailItem:(id)newDetailItem {
    if (detailItem != newDetailItem) {
        [detailItem release];
        detailItem = [newDetailItem retain];
 
        // Update the view.
        navigationBar.topItem.title = detailItem;
	NSString * imageName = [NSString stringWithFormat:@"%@.png",detailItem];
	[self.fruitImageView setImage:[UIImage imageNamed:imageName]];
    }
 
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];
    }
}

Most of this code has been added by the template and I won’t discuss it too much in this tutorial.  But for now, the important additions are the lines that load the image based on  the name of the fruit and the one below it that sets the image property of the image view.

There you have it! Build and go and the application should function as mentioned.  Here is another screenshot of the final product.

Another Cool Feature Of SplitViewController

When in vertical mode, the SplitViewController gives you another new UI element called the UIPopOverView.  Collin will have a tutorial up soon on this view, but the figure below shows you what I’m talking about.

When the device is vertical, it will automatically rotate your view and provide a UIPopoverView when the “Master List” button is pretty. (BTW this button is also customizable).

You may download the source for this tutorial here iPadHelloWorld.zip.
Blancer IPhone IPad Tutorials!!

iPhone OS 4.0 Predictions

iPhone OS 4.0 Predictions

Wow, April is a big month for Apple. iPad release on the 3rd, probably laptop debuts later this month, and iPhone 4.0 announcement coming up on the 8th. Lots to cover. In the spirit of iCodeBlog I present to you a list of stuff to look for in iPhone OS 4.0.

Syncing

  • Wi-Fi Syncing – This is something I would love, but as anyone with an iPhone knows, USB syncing takes forever as it is…So this might not happen
  • iBooks on iPhone – Amazon has the books you buy from them viewable on Mac Computers, iPads and iPhones, Apple is going to address this almost certainly.
  • iTunes Home may be enhanced. An underdeveloped feature in the previous version of iTunes and something people will be using more and more with iPad apps being more expensive.

Interface

  • Home Screen enhancements. Look at the home screen on my iPad. What an incredible waste of space! I need to see upcoming appointments, the weather a twitter feed, incoming emails. But right now when my iPad is locked I see 900 x 700 of background art. This seems like it is a hint that Apple will be making their lock screens more customizable to me.
  • Spotlight. To give credit where it is due, my brother originally (twitter @sruffenach) mentioned this, now it is all I think about when I use spotlight. Once again there is a huge waste of space. When you ender the spotlight view (iPhone or iPad) once again there is a huge amount of wasted space. At the very least your dock applications should slide up and be available until you type something into the search. I think this is an underused section of the iPhone and iPad OS and we shall see if Apple enhances it.
  • New interface elements. The iPad introduced a few new view controllers to the SDK. Things like UISplitViewController, MPMoviePlayerViewController are as of now iPad only. It doesn’t seem to make a ton of sense for some of these UI elements to be on a screen as small as the iPhone, so I think we are going to see the separation of the iPhone and iPad OS’s. Apple is going to need to be careful here on how is makes the SDK’s distinct, as developers will want to have as much time saved developing for either iPhone or iPad. I think we will see Apple’s position on this evolving echo system of SDK’s.
  • Application Switching – This speaks to the idea of multi tasking, which I will talk about in a minute. But I see the iPhone OS gaining more rapid application switching mechanisms in coming releases. Right now to go from any one app to any other there are 2 methods; 1. Go to homescreen, pick another app 2. Click a link in an app that automatically brings up another. Applications are going to reach the complexity where several apps on one iPhone or iPad will be able to handle file types like .PDF. I imagine Apple introducing a mechanism to choose the app which you want to handle the file.
  • Once again, looking at the iPad, it is likely that Apple pushes the idea of the iPhone working in any orientation. The homescreen is likely to change now when the device is tilted into landscape mode.

Multitasking

  • Everyone talks about this, so it seems like will need to mention it somehow. With Android attaching Apple specifically in the Droid commercial this is something Apple will likely tackle. I have a feeling it won’t be complete multitasking. But I most certainly could imagine some tests that an app would need to pass to be “multi task” approved. We’ll see how Apple handles it.
  • If this muti tasking thing does happen expect to see the iPhone version of Expose. Apple has already brought aspects of the OS X desktop to the iPhone with spotlight. Expect to see more of thi

Ads

  • Apple bought Quattro, an ad company a few months back. Apple already has a choke hold around iPhone app distribution, but no control of ads. With Google buying AdMob, this will most certainly be a topic of discussion.

Misc

  • People have been talking printers
  • Extended video streaming API in preparation for vid chat stuff
  • Faster, faster, faster. As you may have seen, dismantling the iPad reveals a chip very similar in design to the iPhone 3GS chip. The responsiveness on the iPad is much better then that of the iPhone and I imaging that general speed of apps will be a big component of 4.0, as it was for 3.0 and the 3GS.

Thats all I got for now. If you guys have any tips, hunches or dreams about iPhone OS 4.0 let us know in the comments.

Follow me on Twitter! @cruffenach

iPhone Coding – Turbo Charging Your Apps With NSOperation

iPhone Coding – Turbo Charging Your Apps With NSOperation

Introduction

So, let’s face it, MANY applications in the app store are “Clunky”.  They have jittery interfaces, poor scrolling performance, and the UI tends to lock up at times.  The reason? DOING ANYTHING OTHER THAN INTERFACE MANIPULATION IN THE MAIN APPLICATION THREAD!

What do I mean by this? Well, I am essentially talking about multithreading your application.  If you don’t know what is meant by multithreading, I suggest you read up on it and return to this post OR don’t worry about it because you don’t need much threading knowledge for this tutorial.  Let’s dig in and I’ll give you an example of the problem.

The Problem

When you create an application, the iPhone spawns a new process containing the main thread of your application.  All of interface components are run inside of this thread (table views, tab bars, alerts, etc…).  At some point in your application, you will want to populate these views with data.  This data can be retrieved from the disk, the web, a database, etc… The problem is: How do you efficiently load this data into your interface while still allowing the user to have control of the application.

Many applications in the store simply ‘freeze’ while their application data is being loaded.  This could be anywhere from a tenth of a second to much longer. Even the smallest amount of time is noticeable to the user.

Now, don’t get me wrong, I am not talking about applications that display  a loading message on the screen while the data populates.  In most cases, this is acceptable, but can not be done effectively unless the data is loaded in another thread besides the main one.

Here is a look at the application we will be creating today:

Let’s take a look at the incorrect way to load data into a UITableView from data loaded from the web.   The example below reads a plist file from icodeblog.com containing 10,000 entries and populates a UITableView with those entries.  This happens when the user presses the “Load” button.

Wrong (download this code here to see for yourself)

@implementation RootViewController
@synthesize array;
 
- (void)viewDidLoad {
    [super viewDidLoad];
 
    /* Adding the button */
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Load"
        style:UIBarButtonItemStyleDone
        target:self
        action:@selector(loadData)];
 
    /* Initialize our array */
    NSMutableArray *_array = [[NSMutableArray alloc] initWithCapacity:10000];
    self.array = _array;
    [_array release];
}
 
// Fires when the user presses the load button
- (void) loadData {
 
    /* Grab web data */
    NSURL *dataURL = [NSURL URLWithString:@"http://icodeblog.com/samples/nsoperation/data.plist"];
 
    NSArray *tmp_array = [NSArray arrayWithContentsOfURL:dataURL];
 
    /* Populate our array with the web data */
    for(NSString *str in tmp_array) {
        [self.array addObject:str];
    }
 
    /* reload the table */
    [self.tableView reloadData];
}
 
#pragma mark Table view methods
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.array count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier] autorelease];
    }
 
    /* Display the text of the array */
    [cell.textLabel setText:[self.array objectAtIndex:indexPath.row]];
 
    return cell;
}
 
- (void)dealloc {
    [super dealloc];
    [array release];
}
 
@end

“Looks good to me”, you may say.  But that is incorrect.  If you run the code above, pressing the “Load” button will result in the interface ‘freezing’ while the data is being retrieved from the web.  During that time, the user is unable to scroll or do anything since the main thread is off downloading data.

About NSOperationQueue And NSOperation

Before I show you the solution, I though I would bring you up to speed on NSOperation.

According to Apple…

The NSOperation and NSOperationQueue classes alleviate much of the pain of multi-threading, allowing you to simply define your tasks, set any dependencies that exist, and fire them off. Each task, or operation, is represented by an instance of an NSOperation class; the NSOperationQueue class takes care of starting the operations, ensuring that they are run in the appropriate order, and accounting for any priorities that have been set.

The way it works is, you create a new NSOperationQueue and add NSOperations to it.  The NSOperationQueue creates a new thread for each operation and runs them in the order they are added (or a specified order (advanced)).  It takes care of all of the autorelease pools and other garbage that gets confusing when doing multithreading and greatly simplifies the process.

Here is the process for using the NSOperationQueue.

  1. Instantiate a new NSOperationQueue object
  2. Create an instance of your NSOperation
  3. Add your operation to the queue
  4. Release your operation

There are a few ways to work with NSOperations.  Today, I will show you the simplest one: NSInvocationOperation.  NSInvocationOperation is a subclass of NSOperation which allows you to specify a target and selector that will run as an operation.

Here is an example of how to execute an NSInvocationOperation:

NSOperationQueue *queue = [NSOperationQueue new];
 
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
    selector:@selector(methodToCall)
    object:objectToPassToMethod];
 
[queue addOperation:operation];
[operation release];

This will call the method “methodToCall” passing in the object “objectToPassToMethod” in a separate thread.  Let’s see how this can be added to our code above to make it run smoother.

The Solution

Here we still have a method being fired when the user presses the “Load” button, but instead of fetching the data, this method fires off an NSOperation to fetch the data.  Check out the updated code.

Correct (Download the source code here)

@implementation RootViewController
@synthesize array;
 
- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Load"
       style:UIBarButtonItemStyleDone
       target:self
       action:@selector(loadData)];
 
    NSMutableArray *_array = [[NSMutableArray alloc] initWithCapacity:10000];
    self.array = _array;
    [_array release];
}
 
- (void) loadData {
 
    /* Operation Queue init (autorelease) */
    NSOperationQueue *queue = [NSOperationQueue new];
 
    /* Create our NSInvocationOperation to call loadDataWithOperation, passing in nil */
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
        selector:@selector(loadDataWithOperation)
        object:nil];
 
    /* Add the operation to the queue */
    [queue addOperation:operation];
    [operation release];
}
 
- (void) loadDataWithOperation {
    NSURL *dataURL = [NSURL URLWithString:@"http://icodeblog.com/samples/nsoperation/data.plist"];
 
    NSArray *tmp_array = [NSArray arrayWithContentsOfURL:dataURL];
 
    for(NSString *str in tmp_array) {
        [self.array addObject:str];
    }
 
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
}
 
#pragma mark Table view methods
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.array count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
 
    [cell.textLabel setText:[self.array objectAtIndex:indexPath.row]];
 
    return cell;
}
 
- (void)dealloc {
    [super dealloc];
    [array release];
}

As you can see, we haven’t added much code here, but we have GREATLY improved the overall user experience.  So, what did I do exactly?

  1. Moved all of the processing (downloading) code from the loadData method to another method that could be run asynchronously
  2. Created a new instance of NSOperationQueue by calling [NSOperationQueue new]
  3. Created an NSInvocationOperation to call our method loadDataWithOperation
  4. Added the operation to the queue
  5. Released the operation
  6. When the Data has been downloaded, we reload the table data in the main thread since it’s a UI manipulation

One thing to note here is we never actually tell the operation to run.  This is handled automatically in the queue.   The queue will figure out the optimal time run the operation and do it for you.

Now that you have your downloading and processing in a separate thread, you are now free to add things such as a loading view.

I will be expanding on this tutorial in the coming week and showing you how to cache data and display old data to the user while the new is loading.  This is a popular technique used in many Twitter and News applications.

That concludes today’s tutorial.

Post questions in the comments or Ping me on Twitter.

Happy iCoding!

Adding TwitPic to your Application

Adding TwitPic to your Application

Introduction

Back in July of last year. Brandon put up a post showing you how to integrate twitter into your application. Today I am going to take the class he made last year and add a new class which will let you post to twit pic. First lets do a little overview of what tools we need for this.

Required Tools

Twit pic is an awesome service. They have created a whole public API, that anyone can use to host a picture and post a tweet with a link to it. You can see the TwitPic API, and all its functionality here.The API is pretty simple, with only 2 methods.

  • uploadAndPost
  • upload

We are going to only be implement access to the uploadAndPost method. In order to use the API we need to use an HTTP POST method. While Apple provides NSURLConnection to take care of operations like this, we are going to use a better third party framework called ASIHTTPRequest. You can find ASIHTTPRequest to download here. I will go over the steps to get it installed. Just download the files for right now. You will also need to download some utility files that Apple created for users called Reachability. You can find those files here.

Preparing a project to use ASIHTTPRequest

  1. Before we add the method into out TwitterRequest class, we have to do a bit of preparation with a project we want to use this framework witb. First think to do is to add ASIHTTPRequest and the Reachability classes into your application.
  2. Now we have to add some frameworks to out project by “Editing the active target”. Go to Project ->  Edit Active Target “TwitPic”
  3. Add in the following targets: CFNetwork.framework, SystemConfiguration.framework and libz.1.2.3.dylib

Using ASIHTTPRequest to contact TwitPic

Now if we compile we should see no errors, and we will be able to use ASIHTTPRequest in our new method in out TwitterRequest class. The method to communicate with TwitPic is actually going to be very short. We need to create the method to send the picture and fill in the methods to handle the response. Lets take a look at what these methods look like.

Method to send picture to TwitPic

Here we are going to pass in the photo for twit pic along with the delegate that is using out class. This pertains back to the design decision made when developing the original TwitterRequest class. Look back at the first post for expansion on this. Here we create an instance of an ASIFormDataRequest. request is an instance variable I declared in the TwitterRequest header. Pass in the proper values for the proper keys, following along with the TwitPic API. We are going to start and Asynchronous request here, so the UI does not freeze while the picture is being uploaded.

-(void)statuses_update:(NSString *)status withPhoto:(NSData*)photoData delegate:(id)requestDelegate requestSelector:(SEL)requestSelector {
     isPost = YES;
     // Set the delegate and selector
     self.delegate = requestDelegate;
     self.callback = requestSelector;
     // The URL of the Twitter Request we intend to send
     NSURL *url = [NSURL URLWithString:@"http://twitpic.com/api/uploadAndPost"];
     // Now, set up the post data:
     request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
     [request setDelegate:self];
     [request setData:photoData forKey:@"media"];
     [request setPostValue:username forKey:@"username"];
     [request setPostValue:password forKey:@"password"];
     [request setPostValue:status forKey:@"message"];
     // Initiate the WebService request
     [request startAsynchronous];
}

Methods to handle response

We need to handle two types of response from TwitPic. Either the request will finish, or the request will error. If the request finishes the following will be called. We check that the delegate set for the TwitterRequest class is present and that is responds to the selector that was passed in. If it does, the TwitterRequest class will respond back to the class using it.

- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(@"%@", [request responseString]);
// do something with the data
     if(delegate && callback) {
          if([delegate respondsToSelector:self.callback]) {
               [delegate performSelector:self.callback withObject:receivedData];
          } else {
               NSLog(@"No response from delegate");
          }
     }
// release the connection, and the data object
     [request release];
}

This is the class that should be used to handle errors. This for example could display a UIAlertView saying that an error occurred.

- (void)requestFailed:(ASIHTTPRequest *)request {
     NSError *error = [request error];
}

You can download the Header and Main for the updated TwitterRequest class here.

App Store Overpopulation

App Store Overpopulation

The number of applications in the app store is approaching 100,000. The quality of applications in this massive of a marketplace is hard to measure. Apple provides the star ratings for applications but I like to have a few more sources. Check out:

app.itize.us

app.itize.us is a site highlighting the best of emerging apps in the store. The site is really well categorized and will surely show you some hidden great apps.

Fresh Apps

Fresh Apps is a user driven review site to supplement the star and comment sections of the App Store which was created by iCodeBlog contributor Brandon Trebitowski (brandontreb). User can get an account and set apps as “Fresh” to boost their popularity on the site.

Touch Arcade

Touch Arcade is a very popular iPhone game review and preview site. The site was created by the founder of Mac Rumors and is a one stop show for a look at the most quality games on or coming to the store.

iPhone Coding Recipe – Shortening URLs

iPhone Coding Recipe – Shortening URLs

I had some a to shorten URLs for an in-application Twitter client I’m working on and thought I would share my simple solution with you guys.

It’s actually pretty straight forward and can be done in 1 line of code.  I have broken it up into several for clarity.

NSString *url    = @"http://brandontreb.com";
NSString *apiEndpoint = [NSString stringWithFormat:@"http://api.tr.im/v1/trim_simple?url=%@",url];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
		 encoding:NSASCIIStringEncoding
		 error:nil];
NSLog(@"Long: %@ - Short: %@",url,shortURL);
 
// Outputs Long: http://brandontreb.com - Short: http://tr.im/MRDd

Pretty easy huh?

The magic here is in a method that Apple gave us as part of NSString. This method is called stringWithContentsOfURL. It will easily allow you to grab the text of any remote source.

I have used Tr.im as an example here because their service is very easy to use and has little overhead.  I would have used bit.ly but they return a JSON string which would then have to be parsed.  Tr.im’s trim_simple service simply outputs the string of the shortened URL.

Sure Twitter may shorten links for you automatically, but what if you want to use a custom service? Or,…wait for it… use it for something other than Twitter (please post in the comments if you do. I would love to hear some other uses :) )

Questions? Comments? Complaints?

Happy iCoding

Getting Started with iPhone Development

Getting Started with iPhone Development

Absolute Beginner’s Guide to iPhone Development | Getting Started with iPhone Development | Hello World iPhone Tutorial. This tutorial is focused on getting “Hello World” application running on iPhone simulator. 10 Easy step Tutorial to create your hello world iPhone application.

Related posts:

  1. Beginner iPhone SDK Hello World Tutorial [Example & Code] In this tutorial I will walk to you through creating…
  2. iPhone SDK Tutorial – {Part 4} Tips for UITableView Design [Add Header, Footer, Background Images & change Design] UITableView Tutorial: {Part 4} This tutorial will explain, how you…


Basic Questions before You start iPhone Development

Basic Questions before You start iPhone Development

One person from India asked me few question for iPhone development and below you can find answer’s to those questions. If you have any question regarding iPhone Development, please add in comments and I will try to response them.

1) i am not registered developer so far, i will be registered with in 2,3 dayes.. so […]

Related posts:

  1. Bypass Code Signature & Published Your Application on Cydia Published iPhone Application On Cydia. Build your application for jail…
  2. iPhone Video Tutorial: Bypassing Code Signature in Xcode & Installing jail-break application to iPhone Video Tutorial to bypass code signature in Xcode and installing…
  3. Five things you should know for building iPhone applications Five things you know before you start developing iPhone applications:…


Five things you should know for building iPhone applications

Five things you should know for building iPhone applications

Five things you know before you start developing iPhone applications:
1. You need a mac os x( mac mini, or mac book or mac pro, anything you like)

2. To submit your work to apple you need a apple developer license as well.
3. The SDK is free to download, so you can build you application and
test it on simulator without any cost. But if you want to test it on
your iPhone/iPod touch or submit it to apple store, you must have a
developer license.

4. To test your application, you must have either iPod or iPhone
because Simulator and device behaves differently on some features like
memory.  So I highly recommand you to buy one device as well.

5. Programming language is Objective – C and its very similar to
C/C++, even a Java developer like me didnt spend much time to understand
the language.

iPhone Tutorial for Retrieving Contact information from AddressBook

iPhone Tutorial for Retrieving Contact information from AddressBook

Introduction
In this tutorial I will explain how you can retrieve a Contact(s) from your AddressBook (in iPhone) though coding. In iPhone you can retrieve contact information stored in address book easier then you can think. You can retrieve their pictures (photos), email address(es) and anything user stored in AddressBook. Note: iPhone provided easy access to […]

Related posts:

  1. get Image from Contact stored in AddressBook [iPhone] Retrieve Images from AddressBook…
  2. iPhone Tutorial for Creating a Splash Screen Introduction: Some people asked me about creating a splash screen…
  3. iPhone Programming Tutorial {Part 7}: Adding Pictures into your table using Interface builder Creating iPhone Application: Introduction: I am going to write series…


iPhone Programming Tips: Dialing number, opening Email & SMS applications

iPhone Programming Tips: Dialing number, opening Email & SMS applications

Introduction
iPhone SDK did not gives you full control over iPhone functionality. But there are few things you can do using iPhone SDK, like, you can dial a number from your application, you can open an email and SMS client from your application.
Request Full Filled
This tutorial is for Sudha who requested for this in “Request iPhone […]

Related posts:

  1. iPhone Programming Tutorial {Part 7}: Adding Pictures into your table using Interface builder Creating iPhone Application: Introduction: I am going to write series…
  2. Five things you should know for building iPhone applications Five things you know before you start developing iPhone applications:…
  3. iPhone Programming Tutorial: Complete List of UITableView Tutorials + Videos Complete List of UITableView tutorials plus few video tutorials as…


iPhone SDK Tutorial – {Part 5}: Add, Delete & Reorder UITableView Rows

iPhone SDK Tutorial – {Part 5}: Add, Delete & Reorder UITableView Rows

This tutorial will explain, how you can change the UITableView data. In this tutorial, I will add, delete and re-order rows in UITableView. I will be using navigation code here.

Related posts:

  1. iPhone Programming Tutorial: {Part 3} Grouped UITableView I am going to write series of UITableView tutorials (Video…
  2. iPhone Programming Tutorial – {Part 1} UITableView using NSArray Creating iPhone Tutorial Introduction: I am going to write series…
  3. iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView] This tutorial will help you to create custom rows in…


iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView]

Introduction:

I am going to write series of UITableView tutorials (Video Tutorials as well). My target is to make the customized UITableView using UITableViewCell which is requested on “Request Tutorial” page. Following are the list of tutorials, which I will be posting on this blog:

1. Create a Simple UITableView [Populate UITableView With Array]
2. Navigatation in UITableView [Navigatation on UITableView using didSelectRowAtIndexPath]
3. Grouped UITableView [Using Interface builder]
4. Tips for UITableView Design [Change UITableView properties i.e background colour, accessory type, add footer and header]
5. Add, Delete & Re-order UITableView rows
6. Creating UITableView using UITableViewCell
7. Adding Pictures into your UITableView using Interface builder
8. UITableView & UITableViewCell examples and tips

[Note: If you want more tutorials on UITableView or UITableViewCell, then add a comment on “Request Tutorial” Page]

Idea of this tutorial:

UITableViewCell tutorial will explain how you can use UITableViewCell in UITableView. Custom UITableViewCell using Interface builder makes table view design very easy. Using UITableViewCell gives you lot of customization over the design of each row. You can easily reduce number of code lines by using UITableViewCell (i.e reduce customization code and easy to manage your table). There are few things which are little hard to do using UITableView but using UITableViewCell they are easily manageable i.e you can manage your cell code in a separate class, you can change the design of cell using nib files more easily then writing codes. So in my point of view, custom UITableViewCell using Interface builder makes your life more easy while developing applications for iPhone.

So in this tutorial, i will write only UITableViewCell and link it with UITableView. I will be using part 2 code, which you can grab from here. Final output of this code will be same as part two but to change the design on table will be really simple. You can watch the video tutorial at the end to skip all the text.

customize UITableView using UITableViewCell
customize UITableView using UITableViewCell

Steps to follow

Follow these steps to achieve the output like above:

Step 1: Open the SimpleTable project in Xcode (you can grab this code from here. [Note: I am using UITableView part 2 code here]). In Xcode, ‘Group and Panel’ right click on classes, select >Add> New File..>. Now select UITableViewCell and name it ‘TableViewCell’, press finished.

Add UITableViewCell
Add UITableViewCellSelect UITableViewCell from wizard
Select UITableViewCell from wizard

Name the UITableViewCell class
Name the UITableViewCell class

Step 2: Now in ‘TableViewCell.h’ file add following code before @end and after #import:

1.@interface TableCellView : UITableViewCell {
2.IBOutlet UILabel *cellText;
3.}
4.
5.- (void)setLabelText:(NSString *)_text;

Step 3: Now open ‘TableViewCell.m’ file and write a setter method for label like this:

1.- (void)setLabelText:(NSString *)_text;{
2.cellText.text = _text;
3.}

Step 4: Open SimpleTableViewController.h file and write following:

1.#import "TableCellView.h"
2.@interface SimpleTableViewController : UIViewController {
3.IBOutlet UITableView *tblSimpleTable;
4.NSArray *arryData;
5.IBOutlet TableCellView *tblCell;
6.}

Step 5: Open SimpleTableViewController.h file and import ‘TableCellView.h’ at top.

1.#import "TableCellView.h"

In cellForRowAtIndexPath method remove all the code or either comment the code. Add the following code in that method:

01.static NSString *MyIdentifier = @"MyIdentifier";
02.MyIdentifier = @"tblCellView";
03.
04.TableCellView *cell = (TableCellView *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
05.if(cell == nil) {
06.[[NSBundle mainBundle] loadNibNamed:@"TableCellView" owner:self options:nil];
07.cell = tblCell;
08.}
09.
10.[cell setLabelText:[arryData objectAtIndex:indexPath.row]];
11.return cell;

Step 6: Now open NextView.xib file from your Xcode project. Press cmd + shift + s to save as this file, and give it a name TableViewCell and ‘Add’ to ‘SimpleTable’ project:

Save As nib file
Save As nib fileSave As nib file
Name UITableViewCell xib file
Save As nib file
Save nib file

Step 7: Now in TableViewCell.xib file, select ‘View’ and then select Edit>Delete (or press ‘back space’ button) to remove the View from xib file

Save As nib file
Remove View from TableCellView.xibSave As nib file
Deleted View from TableCellView

Step 8: Now press cmd + shift + l to open Library. Drag ‘Table View Cell’ to ‘TableViewCell.xib’ file. Select ‘Table View Cell’ and press cmd + 4 and write ‘TableCellView’ in class and press cmd + 1 and write ‘tblCellView’ in Identifier.

Save As nib file
Add UITableViewCell to nib fileSave As nib file
Assign Class to Table Cell View

Save As nib file
Add Identifier to Table Cell View

Step 9: Now select ‘Files Owner’ and press cmd + 4 and type ‘SimpleTableViewController’ in class. Also press cmd + 2 and drag tblCell to ‘Table View Cell’ like in the below picture:

Save As nib file
Give class name to File’s Owner
Save As nib file
Map UITableViewCell to Table View Controller

Step 10: Now drag a label inside UITableViewCell and select ‘TableViewCell’, drag cellText with label.

Save As nib file
Map Label

Step 11: Save the interface builder and your code. Run the application and you will see the output like this:

Save As nib file
Custom UITableViewCell Output

Looked at bottom pictures to change the color of labels and cell Accessory:

Save As nib file
Change Table Cell View Accessory

Save As nib file
Change Label Text colour

Save As nib file
Label Colour text change

Run the application and you will see the final output.

Save As nib file
Final Output of Custom UITableViewCell

Custom UITableViewCell code

You can grab this code from here.

Now watch me doing it


iPhone Tutorial for Creating a Splash Screen

iPhone Tutorial for Creating a Splash Screen

Introduction:
Some people asked me about creating a splash screen in iPhone. So today I am going to write a simple tutorial on creating splash view for your application. I will write another post on good looking splash page as well. Its really a small thing but have a really good impact on your users.

So lets […]

Related posts:

  1. iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder [UITableView] This tutorial will help you to create custom rows in…
  2. iPhone Programming Tutorial {Part 7}: Adding Pictures into your table using Interface builder Creating iPhone Application: Introduction: I am going to write series…
  3. iPhone Tutorial for Retrieving Contact information from AddressBook Introduction In this tutorial I will explain how you can…