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

Pick Your Own Adventure iPhone Edition

Pick Your Own Adventure iPhone Edition

A few days ago I came across this cool Pick Your Own Adventure game on Twitter from user Peretti. I decided to make a quick renewable application that used UIAlertViews and UIActionSheets to tell the story. We are going to implement the UIAlertView and UIActionSheet protocol methods in order to get the functionality we are looking for. This will be a short project but will show the important methods associated with these views.

Step 1

Start a new view based project called CYOA. If you want to add a background image you can add a UIImageView to your CYOAViewController.xib. You can get the one I used here. But that is not necessary.

Step 2

In your project we are going to create a new object to hold the pieces that compose and given “frame” of a pick your own adventure. A frame of a pick your own adventure game is composed of 6 things as far as I am concerned.

  1. Prompt/Title
  2. Choice 1 Text
  3. Choice 2 Text
  4. Choice 1 Tile
  5. Choice 2 Tile
  6. isEnd

Through the use of these 6 objects we will be able to create a network of what I have called “AdventurePieces”. Create a new file. Make a subclass of NSObject and call it AdventurePiece.

Open AdventurePiece.h and input the following.

#import 
 
@interface AdventurePiece : NSObject {
	NSString *message;
	NSString *choice1;
	NSString *choice2;
 
	AdventurePiece *choice1Piece;
	AdventurePiece *choice2Piece;
 
	BOOL isEnd;
}
 
@property (nonatomic, retain) NSString *message;
@property (nonatomic, retain) NSString *choice1;
@property (nonatomic, retain) NSString *choice2;
 
@property (nonatomic, retain) AdventurePiece *choice1Piece;
@property (nonatomic, retain) AdventurePiece *choice2Piece;
 
@property (assign) BOOL isEnd;
 
-initWithMessage:(NSString*)_message
	 firstChoice:(NSString*)_choice1
	secondChoice:(NSString*)_choice2
	  firstPiece:(AdventurePiece*)_choice1Piece
	 secondPiece:(AdventurePiece*)_choice2Piece
		   isEnd:(BOOL)_isEnd;
 
@end

Step 3

We are now going to implement the initialization method that we defined in our header. Open up AdventurePiece.m and input the following.

#import "AdventurePiece.h"
 
@implementation AdventurePiece
 
@synthesize message;
@synthesize choice1;
@synthesize choice2;
 
@synthesize choice1Piece;
@synthesize choice2Piece;
 
@synthesize isEnd;
 
-initWithMessage:(NSString*)_message
	 firstChoice:(NSString*)_choice1
	secondChoice:(NSString*)_choice2
	  firstPiece:(AdventurePiece*)_choice1Piece
	 secondPiece:(AdventurePiece*)_choice2Piece
		   isEnd:(BOOL)_isEnd
{
	if(self = [super init])
	{
		message = _message;
		choice1 = _choice1;
		choice2 = _choice2;
		choice1Piece = _choice1Piece;
		choice2Piece = _choice2Piece;
		isEnd = _isEnd;
	}
 
	return self;
}
@end

All we need to do in this initialization method is fill in our object parameters appropriately.

Step 4

Now that we have made the object that will facilitate our story we need to go about making the logic to automate bringing up the adventure pieces in the right order. First we are going to define one object in our view controller header. Go to CYOAViewController.h and input the following.

#import
#import "AdventurePiece.h"
 
@interface MakeMyOwnAdventureViewController : UIViewController <UIActionSheetDelegate, UIAlertViewDelegate>  {
 
	AdventurePiece *currentPiece;
}
 
@end

Step 5

With that done we need to do the following final steps.

  1. When the app launches a method should be called that creates a bunch of connected adventure pieces and sets the currentPiece instance variable to the one we desire to start on.
  2. Tell the app to show the currentPiece adventure tile.
  3. Respond to users pushing buttons on the adventure tile by resetting the current piece instance variable.
  4. Pull up a different view when the end of the chain is reached.

For our purposes we will be have UIAlertViews show the parts of the story before the end. And the final piece of our story will be shown in a UIActionSheet. Lets look at each of the code pieces required to finish off our last four steps.

1. When the app launches a method should be called that creates a bunch of connected adventure pieces and sets the currentPiece instance variable to the one we desire to start on.

-(void)makeTheStory {
 
	AdventurePiece *successPiece = [[AdventurePiece alloc] initWithMessage:@"Sparks fly from the red wire but no explosion! Kim Jong Il’s evil plot is foiled!" firstChoice:@"YAY" secondChoice:nil firstPiece:nil secondPiece:nil isEnd:YES];
	AdventurePiece *failPiece = [[AdventurePiece alloc] initWithMessage:@"Cutting the blue wire begins a chain reaction - omg that is bad. Like really bad..Kaboom! What went wrong!?!" firstChoice:@"Too Bad" secondChoice:nil firstPiece:nil secondPiece:nil isEnd:YES];
	AdventurePiece *failPiece1 = [[AdventurePiece alloc] initWithMessage:@"Bad Choice. You Die" firstChoice:@"Too Bad" secondChoice:nil firstPiece:nil secondPiece:nil isEnd:YES];
	AdventurePiece *middlePieceA = [[AdventurePiece alloc] initWithMessage:@"You parachute to North Korea, sneak past guards to a live nuclear bomb. Do you" firstChoice:@"Cut Red" secondChoice:@"Cut Blue" firstPiece:successPiece secondPiece:failPiece isEnd:NO];
	AdventurePiece *middlePieceB = [[AdventurePiece alloc] initWithMessage:@"As you are leaving you notice trained assassins behind you" firstChoice:@"Run" secondChoice:@"Fight" firstPiece:failPiece1 secondPiece:failPiece1	isEnd:NO];
	currentPiece = [[AdventurePiece alloc] initWithMessage:@"You are assigned to a dangerous mission." firstChoice:@"Accept" secondChoice:@"Vacation" firstPiece:middlePieceA secondPiece:middlePieceB isEnd:NO];
}

In this method we make 5 total adventure pieces. This specific pick your own adventure is quite short. It as 3 prompts, 2 choices each with a total of 4 end points. You can see what I mean in this diagram here. The white square are the prompts, the green squares are the choices and the red squares are the final results. We fill in the current piece instance variable as the top most piece and we are done here.

2. Tell the app to show the currentPiece adventure tile.

- (void)viewDidLoad {
 
    [super viewDidLoad];
	[self makeTheStory];
	[self showStoryForCurrentPiece];
}
-(void)showStoryForCurrentPiece {
 
	if([currentPiece isEnd]) {
		UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:[currentPiece message] delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:[currentPiece choice1],@"Retry",nil];
		[actionSheet showInView:self.view];
	}
 
	else {
 
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Your Message" message:[currentPiece message] delegate:self cancelButtonTitle:nil otherButtonTitles:[currentPiece choice1],[currentPiece choice2],nil];
		[alert show];
	}
}

This method should be called every time a new current piece is set. If checks to see if the adventure piece is an ending piece, if it is then an action sheet it created. If it is not an alert view is created. The button titles, and prompts are filled in appropriately.

Respond to users pushing buttons on the adventure tile by resetting the current piece instance variable.

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
 
	if(buttonIndex == 0)
	{
		currentPiece = [currentPiece choice1Piece];
		[self showStoryForCurrentPiece];
	}
 
	else
	{
		currentPiece = [currentPiece choice2Piece];
		[self showStoryForCurrentPiece];
	}
}

When an alert view button is pressed this method will be called. An adventure piece that brings up an alert view should always have connected adventure pieces for both of the possible answers it as. This resets the currentPiece adventure piece and show the current piece again.

Pull up a different view when the end of the chain is reached

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
 
	if(buttonIndex == 1)
	{
		[self makeTheStory];
		[self showStoryForCurrentPiece];
	}
}

If this method is called that means that a action piece that was at the end of a chain was brought up. If the users hits the second button (button id == 1) that means they want to reset the story. This can be performed by building our story again showing the current piece again.

You can change the makeTheStory method to be whatever type of story you want. You can download the project here.

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!

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

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.

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…