Monday, December 20, 2010

Objective C basics

Defining a Class

Much of object-oriented programming consists of writing the code for new objects—defining new classes. In Objective-C, classes are defined in two parts:
  • An interface that declares the methods and instance variables of the class and names its superclass
  • An implementation that actually defines the class (contains the code that implements its methods)

    Class Interface

    The declaration of a class interface begins with the compiler directive @interface and ends with the directive @end. (All Objective-C directives to the compiler begin with “@”.)
    @interface ClassName : ItsSuperclass
    {
    instance variable declarations
    }
    method declarations
    @end
     

    Methods for the class are declared next, after the braces enclosing instance variables and before the end of the class declaration. The names of methods that can be used by class objects, class methods, are preceded by a plus sign:
    + alloc;
    The methods that instances of a class can use, instance methods, are marked with a minus sign:
    - (void)display;
     
     
    If a return or argument type isn’t explicitly declared, it’s assumed to be the default type for methods and messages—an id. The alloc method illustrated earlier returns id.
    When there’s more than one argument, the arguments are declared within the method name after the colons. Arguments break the name apart in the declaration, just as in a message. For example:
    - (void)setWidth:(float)width height:(float)height;
     




Thursday, December 16, 2010

I found the answer to my question. It turns out that if your application records and plays, the iphone will by default reroute your playback to the top speaker (the one by your ear), rather than to the speaker at the bottom of the phone. This was the reason for the low volume. If you add the following code, you can force the iphone to route the audio to the bottom speaker.

UInt32 doChangeDefaultRoute = 1;

AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryDefaultToSpe aker,
sizeof (doChangeDefaultRoute),
&doChangeDefaultRoute);

You also have to include the audiotoolbox framework. The avfoundation framework by itself will not allow this code to work.

Tips & Tricks for conditional iOS3, iOS3.2 and iOS4 code

Tips & Tricks for conditional iOS3, iOS3.2 and iOS4 code

In this post, I'll show you ways to determine which version of iOS you are running on and show you how to write a macro that can both conditionally compile and runtime switch between the code for different versions of iOS.

A project or target that supports multiple versions of iOS

To make an application target that runs on multiple versions of iOS is relatively simple:
  • Set the "Base SDK" in your projects settings to the newest version number of iOS whose features you may want.
  • Set the "iPhone OS Deployment Target" to the oldest version number of iOS that you will support
However, getting the target settings correct is the easy part of the problem. The hard part is using new features on newer iOS versions without breaking the app on older versions.

Running in the 3.1.3 simulator

Before getting to the actual code, it might be worthwhile to discuss how to run your projects in older versions of the simulator.
The simulator is an important part of iOS development (since it is much faster and simpler than running your code on the device). But Apple have removed SDK versions earlier than 3.2 from the current Xcode builds. This makes it hard to verify your apps on earlier devices unless you install on a physical device.
Support for 3.1.3 is relatively important since it is the last version of iOS supported by the original iPhone and iPod Touch and it will be a few months before iOS 4 exceeds 80% of the remaining iPhone and iPod Touch market.
To allow simulation in 3.1.3, you must install an old version of Xcode. If you are a registered iPhone developer, you can download Xcode 3.1.4 for Leopard with iPhone SDK 3.1.3 or Xcode 3.1.4 for Snow Leopard with iPhone SDK 3.1.3. Be careful to install these in a different location to your Xcode 3.2.3 with iOS3.2/iOS4 (either select a different hard disk or rename your existing /Developer directory before you install).
Once you've got an old version of Xcode, you'll want to duplicate your main target and set the Base SDK to 3.1.3 in this duplicate (because it won't exist in this version of Xcode). You should use a second target for this because you shouldn't risk messing with your main target just to run code in the simulator.

Using features from newer iOS versions while supporting older iOS versions

For example, if you want to start an iOS4 background task in an application that you want to run on earlier versions of iOS, then you'll need to use code like this:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
    if ([[UIApplication sharedApplication]
        respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)])
    {
        UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication]
            beginBackgroundTaskWithExpirationHandler:^{}];

        // Perform work that should be allowed to continue in background

        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    }
#endif
There are three important components:
  1. The #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 4000 compile-time conditional. This ensures that if we choose to build this project with a Base SDK lower than 4.0, then it won't cause compile problems. This is essential for running in older versions of the simulator.
  2. The runtime check that UIApplication supports the beginBackgroundTaskWithExpirationHandler method. Since the final release build will be built against the 4.0 SDK (even if users install on SDK 3.0) this runtime check ensures that the method we need is available.
  3. Everything else between the #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 4000 and the #endif is the iPhone OS 4 code.

Making the conditional work less ugly

The problem with the previous code is the compile-time conditional and the runtime check for the presence of methods is cumbersome since you must remember to to both.
If you want to integrate both a compile-time check and a runtime check, a better approach would look like this:
IF_IOS4_OR_GREATER
(
    UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication]
        beginBackgroundTaskWithExpirationHandler:^{}];

    // Perform work that should be allowed to continue in background

    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
);
We can implement this macro as follows:
#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_4_0
#define kCFCoreFoundationVersionNumber_iPhoneOS_4_0 550.32
#endif

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
#define IF_IOS4_OR_GREATER(...) \
    if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_4_0) \
    { \
        __VA_ARGS__ \
    }
#else
#define IF_IOS4_OR_GREATER(...)
#endif
If we want to include something only in OS versions prior to a a specific version, then we don't need the conditional compilation (since we still want the code to appear when compiled in a later version. In this case, only a runtime check is required. You can either do this directly, or for symmetry with other macros, you could use:
#define IF_PRE_IOS4(...) \
    if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_4_0) \
    { \
        __VA_ARGS__ \
    }
Three interesting points to note about these macros:
  1. I use the kCFCoreFoundationVersionNumber to determine the iPhone OS at runtime. There are many examples on the web using [[UIDevice currentDevice] systemVersion] but that method requires a string comparison and potentially handling of major and minor numbers within the string components. A single double comparison is far more straightforward.
  2. I have not used the typical do { x } while (0) wrapper around the macro, so you can simply tack an else onto the end if you choose (and it doesn't need conditional compilation of its own).
  3. I use a variable argument list for the macro. This is so that any number of commas may appear in the contents without causing problems.
A final point... the kCFCoreFoundationVersionNumber definitions may not be in every version of the SDK (each SDK normally contains definitions for versions up to but not including itself), so you should conditionally define them yourself in case they're missing. Here's a handy list:
#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_2_0
#define kCFCoreFoundationVersionNumber_iPhoneOS_2_0 478.23
#endif

#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_2_1
#define kCFCoreFoundationVersionNumber_iPhoneOS_2_1 478.26
#endif

#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_2_2
#define kCFCoreFoundationVersionNumber_iPhoneOS_2_2 478.29
#endif

#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_3_0
#define kCFCoreFoundationVersionNumber_iPhoneOS_3_0 478.47
#endif

#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_3_1
#define kCFCoreFoundationVersionNumber_iPhoneOS_3_1 478.52
#endif

#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_3_2
#define kCFCoreFoundationVersionNumber_iPhoneOS_3_2 478.61
#endif

#ifndef kCFCoreFoundationVersionNumber_iPhoneOS_4_0
#define kCFCoreFoundationVersionNumber_iPhoneOS_4_0 550.32
#endif

Better still: solutions that don't require macros

Better than a simple macro is a simple function. This is a valid solution where the contents of your conditional code does not itself contain OS specific code (only the condition itself requires OS specific logic).
A common example is handing separate layout for iPad and iPhone versions. Ordinarily, if you're compiling for iPad 3.2 and iPhone 3.1.3, you need the following code:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
    if ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] &&
        [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
    {
        // iPad specific layout changes
    }
    else
#endif
    {
        // iPhone layout
    }
You can handle this with a conditional macro like the IF_IOS4_OR_GREATER but a far better solution is:
if (isIPad())
{
    // iPad specific layout changes
}
else
{
    // iPhone layout
}
Where all the conditional pollution is tidily kept in your isIPad() function:
BOOL isIPad()
{
    IF_3_2_OR_GREATER
    (
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
        {
            return YES;
        }
    );
    
    return NO;
}

Conclusion

Apple doesn't exactly make it easy to support old versions of the iPhone SDK. I'm sure they want everyone to keep up to date or buy new devices if their current device can't be updated.
That's not always a realistic attitude for App Store developers. You can't expect all your customers to upgrade as soon as possible.
The important point when writing for multiple versions of the SDK is to keep as few conditionals as possible. You don't want to have thousands of conditionals in your code for supporting different versions. Every conditional is extra testing work since different behaviors must be fully exercised on all different platforms.
While the conditionals and functions I've talked about here will help, if you find yourself needing a lot of conditionals you may also want to consider design changes like instantiating different subclasses for different OS versions.

blend two uiimages

blend two uiimages
 
 
 
UIImage* bottomImage = [UIImage imageNamed:@"bottom.png"];  UIImage* topImage    = [UIImageNamed:@"top.png"];
UIImageView* imageView = [[UIImageView alloc] initWithImage:bottomImage];
UIImageView* subView   = [[UIImageView alloc] initWithImage:topImage];
subView.alpha = 0.5;  // Customize the opacity of the top image.
[imageView addSubview:subView];
UIGraphicsBeginImageContext(imageView.frame.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[subView release];
[imageView release];
[self doWhateverIWantWith: blendedImage];
 
 
 
 
 
 
 

iPhone : warning: no ‘-renderInContext:’ method found – solution

There is a simple solution to this pesky warning:
  1. Add the following to your .h file :
    #import <QuartzCore/QuartzCore.h>
  2. You may also need to add  “CoreGraphics.framework” to your project, if its not already there.
 

Parser Capabilities and Architecture

Parser Capabilities and Architecture

There are two general approaches to parsing and handling XML, each with its own style of API:
  • Tree-based API: This approach maps an XML document into an internal tree structure that conforms to the logical structure described by a schema, then facilitates the navigation and manipulation of that tree. Many tree-based APIs are available, including the DOM (Document Object Model) proposed by the World Wide Web Consortium (W3C). The XML Path Language (XPath), XML Inclusions (XInclude), and XML Pointer Language (XPointer) are WC3 programmatic interfaces for querying and handling the XML in DOM-style tree structures.
  • Event-driven API: In this approach the parser reports parsing events (such as the start and end of each element) to an application as it encounters them. In C-based APIs, this reporting is accomplished through callbacks implemented by the application to handle the types of events. SAX is the best-known example of this style of parsing API. This type of parser is sometimes referred to as a streaming parser.
The NSXMLParser class adopts the event-driven style of parsing. But instead of using callbacks, an NSXMLParser object (or simply, a parser) sends messages to its delegate; it sends a different message for each type of parsing event. As the parser sequentially encounters each item in an XML or DTD file—element, attribute, declaration, entity reference, and so on—it reports it to its delegate (if the delegate implements the associated method), along with any surrounding context. It does nothing with the item except report it.
For example, say you have a simple XML file such as the following:
<?xml version= "1.0" encoding="UTF8">
<article author="John Doe">
<para>This is a very short article.</para>
</article>
The parser would report the following series of events to its delegate:
  1. Started parsing document
  2. Found start tag for element article
  3. Found attribute author of element article, value “John Doe”
  4. Found start tag for element para
  5. Found characters This is a very short article.
  6. Found end tag for element para
  7. Found end tag for element article
  8. Ended parsing document
Both the tree-based and event-based parsing approaches have their strengths and disadvantages. It can require considerable amounts of memory to construct an internal tree representing an XML document, especially if that document is large. This problem is compounded if it becomes necessary to map the tree structure of the parsed document to a more strongly typed, application-specific tree structure.
Event-driven parsing—because it deals with only one XML construct at a time and not all of them at once—consumes much less memory than tree-based parsing. It is ideal for situations where performance is a goal and modification of the parsed XML is not. One such application for event-driven parsing is searching a repository of XML documents (or even one XML document with multiple “records”) for specific elements and doing something with the element content. For example, you could use NSXMLParser to search the property-list preferences files on all machines in a Bonjour network to gather network-configuration information.
Event-driven parsing is less suitable for tasks that require the XML to be subjected to extended user queries or to be modified and written back to a file. Event-driven parsers such as NSXMLParser also do not offer any help with validation (that is, it verifying whether XML conforms to the structuring rules as specified in a DTD or other schema). For these kinds of tasks, you need a DOM-style tree. However, you can construct your own internal tree structures using an event-driven parser such as NSXMLParser.
In addition to reporting parsing events, an NSXMLParser object verifies that the XML or DTD is well-formed. For example, it checks whether a start tag for an element has a matching end tag or whether an attribute has a value assigned. If it encounters any such syntactical error, it stops parsing and informs the delegate.
Although the parser “understands” only XML and DTD as markup languages, it can parse any XML-based language schema such as RELAX NG and XML Schema.

Creating a Tabbar

Creating a Tabbar



  
I haven’t seen many examples of creating a tabbar controller other than “theElements” example from Apple, which is pretty intense. So, what follows is a short snippet from a proof-of-concept application I was recently working on.
The basic idea is as follows: a UITabBarController contains an array of UIViewController objects, and these views are swapped when one of the tabbar buttons is clicked. You can see in the code below how I setup the view controllers that will be displayed for each tab, and add those controllers into the tabbar controller array.

The resulting tabbar looks as follows:

The interface file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
    //  BirdBookAppDelegate.h
 
    #import <UIKit/UIKit.h>
 
    @interface BirdBookAppDelegate : NSObject <UIApplicationDelegate>
    {
      UINavigationController *navigationController;
      UIWindow *portraitWindow;
      UITabBarController *tabBarController;
    }
 
    @property (nonatomic, retain) UINavigationController *navigationController;
    @property (nonatomic, retain) UITabBarController *tabBarController;
    @property (nonatomic, retain) UIWindow *portraitWindow;
 
    @end
The implementation file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//  BirdBookAppDelegate.m
 
    #import "BirdBookAppDelegate.h"
    #import "Bird.h"
    #import "AllBirds.h"
 
    @implementation BirdBookAppDelegate
 
    @synthesize navigationController;
    @synthesize tabBarController;
    @synthesize portraitWindow;
 
    /*************************************************************************/
    - (void) configureUI
    {
      // Create nav-controller for local use
      UINavigationController *localNavController;
 
      // Create portrait window and content view (to hold other views)
      UIWindow *localPortraitWindow;
      localPortraitWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
      self.portraitWindow = localPortraitWindow;
      [localPortraitWindow release];  // Retained by delegate thru above setter
 
      // Set background color
      [portraitWindow setBackgroundColor:[UIColor blackColor]];
 
      // New tabbar controller and array to contain the view controllers
      // There are two (2) view controllers needed
      // One for "Identify Bird" and one for "Lookup Bird"
      tabBarController = [[UITabBarController alloc] init];
      NSMutableArray *localViewControllersArray = [[NSMutableArray alloc] initWithCapacity:2];
 
      /*--------------------------------------------------------------------
       * Setup the 2 view controllers for the different data representations
       *-------------------------------------------------------------------*/
 
      // Root view controller for "Identify Bird"
      IdentifyBirdRootViewController *vc;
      vc = [[IdentifyBirdRootViewController alloc] initWithStyle:UITableViewStylePlain];
      localNavController = [[UINavigationController alloc] initWithRootViewController:vc];
      localNavController.tabBarItem.image = [UIImage imageNamed:@"123.png"];
      [vc release];   // This is now managed by the navigation controller
 
      // Add navigation controller to the local vc array (1 of 2)
      [localViewControllersArray addObject:localNavController];
      [localNavController release]; // Retained by above array
 
      // Root view controller for "Lookup Bird"
      vc = [[LookupBirdRootViewController alloc] initWithStyle:UITableViewStyleGrouped];
      localNavController = [[UINavigationController alloc] initWithRootViewController:vc];
      localNavController.tabBarItem.image = [UIImage imageNamed:@"ABC.png"];
      [vc release];   // This is now managed by the navigation controller 
 
      // Add navigation controller to the local vc array (2 of 2)
      [localViewControllersArray addObject:localNavController];
      [localNavController release]; // Retained by above array
 
      // Point the tab bar controllers view controller array to the array
      // of view controllers we just populated
      tabBarController.viewControllers = localViewControllersArray;
      [localViewControllersArray release]; // Retained thru above setter
 
 
      // Add subview to portrait window to reference the tabbarcontroller
      [portraitWindow addSubview:tabBarController.view];
 
      // Show it
      [portraitWindow makeKeyAndVisible];
    }
 
    /*************************************************************************/
    - (void) applicationDidFinishLaunching:(UIApplication *)application
    {
      // Configure the user interface (tabbar, nav controllers, etc)
      [self configureUI]; 
    }
 
    /*************************************************************************/
    - (void) dealloc
    {
      [tabBarController release];
      [portraitWindow release];
      [navigationController release];
      [super dealloc];
    }
 
    @end

100 Free Courses & Tutorials for Aspiring iPhone App Developers

100 Free Courses & Tutorials for Aspiring iPhone App Developers

Unless you’ve been living under a rock, you know that the iPhone is a big deal and it’s one of the most popular subjects of development these days. Lots of developers are creating their own iPhone apps, and with the right know-how, you can too. Check out our list of courses and tutorials to learn everything that’s important about developing for the iPhone.
University
Here you’ll find iPhone development courses offered by top universities.
  1. iPhone Application Programming: Learn about programming for the iPhone from Stanford on iTunes. [Stanford]
  2. Introduction to iPhone Application Development: Use this course’s posted slides to get a crash course in iPhone application development. [MIT]
Apple Resources
You can learn about iPhone development straight from the source with these Apple documents.
  1. Getting Started with iPhone: Here you’ll find a general introduction to iPhone development. [Apple]
  2. Object-Oriented Programming with Objective-C: This document offers an excellent guide for object oriented programming. [Apple]
  3. Networking & Internet Coding How-Tos: In this resource, you will find lots of great advice for networking and Internet development on the iPhone. [Apple]
  4. Getting Started with Audio & Video: Use this document to get started with audio and video features in iPhone applications. [Apple]
  5. Your First iPhone Application: This introductory tutorial offers a step by step description of getting started with an iPhone application. [Apple]
  6. Getting Started with Performance: This guide offers an introduction to improving the performance on iPhone apps. [Apple]
  7. iPhone Application Programming Guide: Get an introduction to the iPhone OS and development process. [Apple]
  8. iPhone OS Technology Overview: Learn about the iPhone OS and its technologies from this guide. [Apple]
  9. Getting Started with Data Management: Here you’ll find a reference that will help you with data management. [Apple]
  10. Security Overview: Get an understanding of the security concepts on the iPhone from this resource. [Apple]
  11. Performance Overview: Get a look at the factors that determine performance through this guide. [Apple]
  12. Resource Programming Guide: Check out this resource to learn how to work with nib and bundle resources.
  13. Getting Started with User Experience: This document offers an introduction to constructing iPhone application user interfaces. [Apple]
  14. iPhone Human Interface Guidelines: Follow these guidelines to make sure your iPhone app has a good human interface. [Apple]
  15. iPhone Development Guide: Use this development guide to get an introduction to creating web apps on the iPhone. [Apple]
  16. Data Formatting Programming Guide for Cocoa: This guide will teach you how to use Cocoa formatters for data. [Apple]
  17. Getting Started with Tools: You will find a guided introduction to the Xcode toolset from this document. [Apple]
  18. Data Management Coding How-tos: Get answers to common data management coding questions. [Apple]
  19. Introduction to Cocoa Application Tutorial: You’ll need at least a base level understanding of Cocoa for iPhone development, which you can check out in this tutorial. [Apple]
  20. Core Animation Programming Guide: Follow this guide to get the main components and services of Core Animation. [Apple]
  21. Coding Guidelines for Cocoa: In this guide, you’ll learn about naming guidelines for the Cocoa API as well as design advice. [Apple]
  22. Getting Started with Graphics and Animation: Follow this guide for an introduction to 2D and 3D graphics and animation. [Apple]
  23. Learning Objective-C: A Primer: Check out this document once you’ve worked through object oriented programming and Cocoa. [Apple]
  24. Cocoa Fundamentals Guide: You’ll learn about the basic concepts, terminology, and more in Cocoa from this guide. [Apple]
  25. Graphics and Animation Coding How-Tos: In this resource, you’ll find lots of great tips and advice for graphics and animation on the iPhone. [Apple]
Getting Started
Get an introduction to iPhone development through these tutorials.
  1. iPhone App Development-Where to Start: This tutorial will teach you how to get started in iPhone app development. [The Daleisphere]
  2. Bootstrap: Learn a few pointers for iPhone development from this resource. [furbo]
  3. Learn How to Develop for the iPhone: This tutorial will show you how to build an alternate page and style sheet for the iPhone. [NETTUTS]
  4. iPhone Application Development, Step By Step: In this tutorial, you will find a step by step guide to creating a simple iPhone game. [Open Laszlo]
  5. First iPhone Application: Get a brief introduction to creating your first iPhone application. [iPhone SDK Articles]
  6. iPhone Dev: Check out this PDF to get a tutorial for iPhone development. [Lucas Newman]
  7. iPhone App Development for Web Hackers: Use this tutorial to learn about geo-location features and beginner development tips. [How to Iphone Application]
  8. How to Write an iPhone App: This tutorial gives you a basic look at what it takes to write an iPhone application. [Webmonkey]
  9. iPhone App Development for Web Hackers: In this article, you’ll learn about web hacking development for the iPhone. [Dominiek]
  10. Writing Your First iPhone Application: Bill Dudney will walk you through all of the tools and pieces of knowledge you’ll need to write your first iPhone application. [The Pragmatic Bookshelf]
  11. Cocoa Touch Tutorial: iPhone Application Example: This tutorial will show you how to make a very basic Cocoa Touch application with Interface Builder. [Cocoa Is My Girlfriend]
  12. Building an iPhone app in a day: Check out this tutorial to see how you can build a useful app quickly. [The Bakery]
  13. Seven Things All iPhone Apps Need: Check out this list to see what’s essential when creating an iPhone app. [APCmag]
  14. Put Your Content in My Pocket: Learn how to use the iPhone web browser to your advantage from this article. [A List Apart]
  15. iPhone Training Course: Become a master at writing iPhone applications through this course. [Rose India]
  16. So you’re going to write an iPhone app…: Learn about code reuse, memory, and more from this tutorial. [furbo]
  17. Learn How to Develop for the iPhone: Check out this tutorial to see how to build an alternative page and style sheet for the iPhone. [Net Tuts]
  18. Developing for the iPhone: This resource will show you how to develop ASP.NET applications for the iPhone. [Dot Net Slackers]
  19. Getting Started with iPhone Development: Ed Burnette offers a basic introduction to iPhone development. [ZDnet]
Tools
These tutorials will teach you how to use specific tools in order to create iPhone apps.
  1. Make an iPhone App Using the Envato API: Make your own iPhone app with the Envato API with the help of this tutorial. [Net Tuts]
  2. Developing iPhone Applications using Ruby on Rails and Eclipse: Learn how to detect mobile Safari from a Ruby on Rails application through this tutorial. [IBM]
  3. 14 Essential Xcode Tips, Tricks and Resources for iPhone Devs: Learn how to make sense of xcode with this helpful resource. [Mobile Orchard]
  4. Develop iPhone Web Applications with Eclipse: This tutorial will help you learn how to create iPhone applications with Aptana’s iPhone development plug-in. [IMB]
  5. Build an iPhone Webapp in Minutes with Ruby, Sinatra, and iUI: You can learn how to quickly put together an iPhone app with these tools. [Mobile Orchard]
  6. iPhone Development with PHP and XML: In this tutorial, you’ll get a look at developing custom applications for the iPhone. [IBM]
Details
These tutorials cover all of the important details in iPhone app development.
  1. Avoiding iPhone App Rejection from Apple: This tutorial holds the secrets to making sure your iPhone app makes the cut. [Mobile Orchard]
  2. Landscape Tab Bar Application for the iPhone: Follow this tutorial to learn about making the tab bar application support landscape orientation. [Cocoa Is My Girlfriend]
  3. iPhone Programming Tutorial-Using openURL to Send Email from Your App: This tutorial explains how you can send email through applications, and even pre-fill fields. [iCode]
  4. Multi Touch Tutorial: This tutorial will show you how you can respond to a tap event. [iPhone SDK Articles]
  5. Create a Navigation-Based Application: This tutorial will teach you how to create and run a navigation-based application from XCode.
  6. Advanced iPhone Development: Go beyond the basics with this iPhone development tutorial. [Dot Net Slackers]
  7. Here’s a Quick Way to Deal with Dates in Objective C: Get information on dealing with date fetching through this tutorial. [Howtomakeiphoneapps]
  8. Navigation Controller + UIToolbar: Through this tutorial, you can learn how to add a UIToolbar to an app. [iPhone SDK Articles]
  9. iPhone Asynchonous Table Image: Follow this thorough article to learn about loading multiple images in your iPhone app in an asynchonous manner. [Markj]
  10. Localizing iPhone Apps-Internationalization: You can use resource files to display text in a user’s language-learn how in this tutorial. [iPhone SDK Articles]
  11. Tutorial: JSON Over HTTP on the iPhone: With this tutorial, you’ll get a step by step how-to for JSON web services through an iPhone app. [Mobile Orchard]
  12. Parsing xml on the iPhone: This tutorial will show you how to parse XML using the iPhone SDK. [Craig Giles]
  13. Reading data from a SQLite Database: Here you’ll find a quick tutorial for reading data from a SQLite database. [dBlog]
  14. How to Make an Orientation-Aware Clock: Through this tutorial, you’ll learn about building a simple, orientation-aware clock. [The Apple Blog]
  15. Finding iPhone Memory Leaks: Carefully find iPhone memory leaks by using this tutorial. [Mobile Orchard]
  16. Localizing iPhone Apps: MAke sure that your iPhone app is properly formatted according to a user’s native country or region with the help of this tutorial. [iPhone SDK Articles]
  17. OpenAL Audio Programming on iPhone: Here you’ll get code snippets, learning, and more. [Gehaktes]
  18. 9 iPhone Memory Management Links and Resources: Here you’ll find a variety of iPhone memory management resources that can help you get things under control. [Mobile Orchard]
  19. Parsing XML Files: Get an understanding of how you can parse XML files with this tutorial. [iPhone SDK Articles]
User Interface
These tutorials are all about the user interface and interaction.
  1. UITableView-Drill down table view tutorial: Check out this tutorial to learn how to make a drill down table view. [iPhone SDK Articles]
  2. iPhone Coding-Learning About UIWebViews by Creating a Web Browser: In this tutorial, you’ll learn about UIWebViews through the creation of a browser. [iCode]
  3. Design Patterns on the iPhone: Check out David Choi’s guest lecture on user interface design for the iPhone. [New Jersey Institute of Technology]
  4. UITableView-Adding subviews to a cell’s content view: This tutorial will show you how to customize the UITableViewCell. [iPhone SDK Articles]
  5. Drill down table view with a detail view: Learn how to load a different detail view on the UITabBarController. [iPhone SDK Articles]
  6. Extending the iPhone’s SDK’s UIColor Class: Learn how to extend the iPhone SDK UIColor class, and get code samples from this article. [Ars Technica]
  7. UITableView: Learn how to make a simple index for the table view with this tutorial. [iPhone SDK Articles]
Building Tutorials
Check out these tutorials where you’ll build a specific app, and learn more about iPhone development along the way.
  1. Build a Simple RSS Reader for the iPhone: Get walked through the creation of an RSS reader for a simple feed on the iPhone. [The Apple Blog]
  2. iPhone Gaming Framework: This article offers a look at writing code for iPhone game developers. [Craig Giles]
  3. Build a Simple RSS Reader for the iPhone: Follow this tutorial, and you’ll learn about building a simple iPhone RSS reader.
  4. iPhone Game Programming Tutorial: This multipart tutorial offers a way to learn OpenGL and Quartz for iPhone development. [iCode]
  5. Build your very own Web browser!: Follow this tutorial to learn about the process of building your own iPhone web browser. [dBlog]
  6. iPhone application development, step by step: Find out how to build the iPhone application NEWSMATCH using OpenLaszlo. [OpenLaszlo]
  7. Building an Advanced RSS Reader using TouchXML: Get step by step information for creating an advanced iPhone RSS reader from this tutorial. [DBlog]
  8. iPhone SDK Tutorial: Building an Advanced RSS Reader Using TouchXML: This tutorial will help you learn more about iPhone development by building an advanced RSS reader with TouchXML. [dBlog]
Videos
Watch these videos for a visual guide to iPhone app development.
  1. Basic iPhone Programming: Check out this video to get started with iPhone programming. [iPhone Dev Central]
  2. First Step Towards the App Store: Work towards getting your app in the app store with the help of this tutorial. [You Tube]
  3. Hello World: This tutorial will help you learn the basics of iPhone programming. [iPhone Dev Central]
  4. UITableView iPhone Programming Tutorial: Watch this video to learn how to populate a UITableView. [YouTube]
  5. iPhone App Tutorial 1: Check out this video to quickly learn about Interface Builder. [YouTube]
  6. iPhone IB-Your First App: Watch this tutorial to learn how to use the Interface Builder. [iPhone Dev Central]
  7. Understanding Source Code: Learn how to get started with development on the iPhone through this video tutorial. [YouTube]
  8. How to Make an iPhone App: Create an iPhone app using Jiggy and this tutorial. [YouTube]
  9. iPhone Development with Dashcode: Find out how to develop iPhone applications with Dashcode through this tutorial. [YouTube]
Development Resources
These resources are not courses or tutorials, but they are incredibly valuable resources for beginner iPhone app developers.
  1. iPhone Open Application Development: This book will teach you how to create software for the iPhone environment. [Safari Books Online]
  2. iPhone GUI PSD File: Use this set to get a comprehensive, editable library of iPhone UI assets. [Teehanlax]
  3. 31 iPhone Applications with Source Code: Teach yourself how to create iPhone apps by taking a look at the code in these. [Mobile Orchard]
  4. iPhoney: Using iPhoney, you’ll be able to see how your creation will look on the iPhone. [Market Circle]
  5. 35 Free iPhone Icon Sets: Check out this resource to find a great variety of iPhone icons

Using iPhone SDK MapKit Framework - A tutorial

Recently I was working on an application in which the map was required to be shown with in the application itself. I tried looking for some online resources that could be of some help but did not find any. I was not able to find any good tutorial that explains how can an address be shown on a map with the application. Therefore, I decided to write one and here it is. Hope it will be of some help. Lets create a simple application which displays the address entered by the user on the map within the application. We'll call it MapApp.
  1. First, create a Window based application and name the project as MapApp.
  2. Add the MapKit framework to the project. (Control + Click Frameworks folder -> Add -> Existing Frameworks)
  3. Create a new view controller class and call it MapViewController. Add a text field, button and map view to it.
#import <UIKit/UIKit.h>
    #import <MapKit/MapKit.h>

    @interface MapViewController : UIViewController<MKMapViewDelegate> {
        IBOutlet UITextField *addressField;
        IBOutlet UIButton *goButton;
        IBOutlet MKMapView *mapView;
    }

    @end
4. Now create a xib file named MapView.xib. Set its type to MapViewController and add a UITextField, UIButton and MKMapView to it. This how it will look like.
Make sure you set the delegate for the mapView to the controller class.
5. Once the view is ready, update the MapAppDelegate so that the view controller and the view is loaded.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
        mapViewController = [[MapViewController alloc] initWithNibName:@"MapView" bundle:nil];
        [window addSubview:mapViewController.view];
        [window makeKeyAndVisible];
    }
6. Now, build the app and check if the view appears correctly or not. We now have the UI ready for entering the address and button for updating the location in the map.
7. Add the class for showing the annotation on the location. Lets call this class as AddressAnnotation.
@interface AddressAnnotation : NSObject<MKAnnotation> {
        CLLocationCoordinate2D coordinate;
        NSString *mTitle;
        NSString *mSubTitle;
    }
    @end

    @implementation AddressAnnotation

    @synthesize coordinate;

    - (NSString *)subtitle{
        return @"Sub Title";
    }

    - (NSString *)title{
        return @"Title";
    }

    -(id)initWithCoordinate:(CLLocationCoordinate2D) c{
        coordinate=c;
        NSLog(@"%f,%f",c.latitude,c.longitude);
        return self;
    }
    @end
This class will basically show the title and the subtitle of the location on the map.
8. Lets add the function that will be called when the 'Go' button is tapped and this will contain the code that will actually display the address location on the map. We call that action as showAddress
- (IBAction) showAddress {
        //Hide the keypad
        [addressField resignFirstResponder];
        MKCoordinateRegion region;
        MKCoordinateSpan span;
        span.latitudeDelta=0.2;
        span.longitudeDelta=0.2;

        CLLocationCoordinate2D location = [self addressLocation];
        region.span=span;
        region.center=location;
        if(addAnnotation != nil) {
            [mapView removeAnnotation:addAnnotation];
            [addAnnotation release];
            addAnnotation = nil;
        }
        addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
        [mapView addAnnotation:addAnnotation];
        [mapView setRegion:region animated:TRUE];
        [mapView regionThatFits:region];
     }
9. The map view basically shows the location based on its latitude and longitude but we have the address in the textual form. Therefore we need to convert this into CLLocationCoordinate2D. Note that in the above code we call the function names addressLocation to perform this conversion.
-(CLLocationCoordinate2D) addressLocation {
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", 
                    [addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
    }
    else {
         //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}
The above code reads the address entered in the input box and gets the location from maps.google.com in CSV format. It then gets the latitude and longitude from it. The return code of 200 from google means success.
10. Finally, lets add the delegate function that will display the annotation on the map
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorGreen;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}
This function basically creates a annotation view (a green color pin) with the annotation that we added earlier to the MapView. Tapping on the green pin will display the title and the sub-title.
Finally, here's how the map looks like when loaded.
So this was a very simple example of how a map can be shown from within an application. Hope this was helpful. Let me know your comments/feedback. Click here to download the code.
UPDATE: All this while Google was not looking for API key in the URL - http://maps.google.com/maps/geo?q=address&output=csv
You can obtain your API key here

UIKeyboardTypeNumberPad and the missing "return" key

If you have ever written an iPhone app that requires numeric input, then you surely know about the UIKeyboardTypeNumberPad. And if you have ever used that flavor of the iPhone's keyboard, then you surely know that it lacks one very important feature: The UIKeyboardTypeNumberPad does not have a "return" key.
In fact every other keyboard type (except for the pretty similar UIKeyboardTypePhonePad) does offer the possibility to be dismissed by setting the returnKeyType property of the corresponding UITextInputTraits implementor. So how does one achieve the same effect with the number pad? We have found a workround!
When looking at the number pad, you'll notice that there is an unused space on its bottom left. That's where we are going to plug in our custom "return" key.

To make it short: take a screenshot, cut out the whole backspace key, flip it horizotally, clear its backspace symbol in Photoshop and overlay it with the text that we want on our “return” key. We’ve chosen to label it “DONE”. Now we have the image for our custom button’s UIControlStateNormal. Repeat the whole procedure (with a touched backspace key when taking the screenshot) to get a second image for our button’s UIControlStateHighlighted. Here’s the result:
   
Now back to coding. First we need to know when the number pad is going to be slided up on the screen so we can plug in our custom button before that happens. Luckily there’s a notification for exactly that purpose, and registering for it is as easy as:
 
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardWillShow:) 
                                             name:UIKeyboardWillShowNotification 
                                           object:nil];
 
Don't forget to remove the observer from the notification center in the appropriate place once you're done with the whole thing:
 
[[NSNotificationCenter defaultCenter] removeObserver:self];
Now we’re getting to the heart of it. All we have to do in the keyboardWillShow method is to locate the keyboard view and add our button to it. The keyboard view is part of a second UIWindow of our application as others have already figured out (see this thread). So we take a reference to that window (it will be the second window in most cases, so objectAtIndex:1 in the code below is fine), traverse its view hierarchy until we find the keyboard and add the button to its lower left:
 
- (void)keyboardWillShow:(NSNotification *)note {  
    // create custom button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
    [doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
 
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
            [keyboard addSubview:doneButton];
    }
}
VoilĂ , that’s it! The empty space for our button starts at coordinate (0, 163) and has the dimensions (106, 53). The doneButton method has to be written now of course, but that’s not hard any more. Just make sure that you call resignFirstResponder on the text field that is being edited to have the keyboard slide down.

We’re “DONE”.

iOS4 Map Kit – Draggable Annotation Views


21 Jul
Main Screenshot
Finished Product..
The new iOS4 update included many updates to the frameworks in the iPhone SDK. Today I will go through one of those updates which has to do with the Map Kit framework. Support for draggable map annotations is very useful in a location aware application. You will not always have the network connectivity you require to get an exact location for a user and, lets face it, Google does not always return the exact coordinate we desire. This tutorial will step you through creating a View Based application with a standard Map View and dropping a pin on the users current location. The user will then be able to tap and hold the pin to drag around the map. The callout accessory will show the Latitude and Longitude of the new location. Let’s begin. REMINDER: THESE INSTRUCTIONS ARE FOR iOS4 SDK. WILL NOT WORK WITH EARLIER SDK’s.

Step 1 – Create a new View Based application in XCode. Name is whatever you like. For now on I will refer to your projects name as ProdjectName.
New View Based Project
New View Based Project
Step 2 - Add MapKit.framework and CoreLocation.framework to the project.
Frameworks Needed
Project Frameworks
Step 3 – Open the ProdjectNameViewController.h. Here you will need to add an outlet to the map view and create a CLLocationManager and CLLocation. The CLLocation will keep up with our current location.
1:  @interface ProdjectNameViewController : UIViewController <UIAlertViewDelegate, CLLocationManagerDelegate, MKMapViewDelegate> {
2:     IBOutlet MKMapView* myMapView;
3:
4:     CLLocationManager* locationManager;
5:     CLLocation* currentLocation;
6:  }
7:
8:  @property (nonatomic, retain) IBOutlet MKMapView* myMapView;
9:
10:  @property (nonatomic, retain) CLLocationManager* locationManager;
11:  @property (nonatomic, retain) CLLocation* currentLocation;
12:
13:
14:  @end
You may want to go ahead and open your ProdjectNameView.xib and hook up the map view to the view controller outlet at this time.
Step 4 – Open the ProdjectNameViewController.m. You will need to synthesize the newly created variables and create your delegate methods for the Map View and Location Manager. You can see the full code in the attached project.  In the -viewDidLoad method I set the map view and location manager delegates to self, add a few checks for the location services, and start updating to the users current location.
1:  - (void)viewDidLoad {
2:    [super viewDidLoad];
3:
4:       [myMapView setMapType:MKMapTypeHybrid];
5:       [myMapView setDelegate:self];
6:
7:       locationManager = [[CLLocationManager alloc] init];
8:       [locationManager setDelegate:self];
9:       [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
10:       if(!locationManager.locationServicesEnabled) {
11:            UIAlertView *locationServiceDisabledAlert = [[UIAlertView alloc]
12:                                                                    initWithTitle:@"Location Services Disabled"
13:                                                                    message:@"Location Service is disabled on this device. To enable Location Services go to Settings -> General and set the Location Services switch to ON"
14:                                                                    delegate:self
15:                                                                    cancelButtonTitle:@"Ok"
16:                                                                    otherButtonTitles:nil];
17:            [locationServiceDisabledAlert show];
18:            [locationServiceDisabledAlert release];
19:       }
20:
21:       [locationManager startUpdatingLocation];
22:  }
Step 5 – Let’s go ahead and create 2 new files. The first file will be a MKPlaceMark which we will call CurrentLocationAnnotation and the other will be a MKAnnotationView subclass which we can call AnnotationView.
CurrentLocationAnnotation.h:
1:  #import <MapKit/MapKit.h>
2:
3:  @interface CurrentLocationAnnotation : MKPlacemark {
4:
5:  }
6:
7:  @property (nonatomic, readwrite, assign) CLLocationCoordinate2D coordinate;
8:
9:  @property (nonatomic, retain) NSString *title;
10:  @property (nonatomic, retain) NSString *subtitle;
11:
12:  @end
CurrentLocationAnnotation.m:
1:  #import "CurrentLocationAnnotation.h"
2:
3:
4:  @implementation CurrentLocationAnnotation
5:  @synthesize coordinate;
6:  @synthesize title;
7:  @synthesize subtitle;
8:
9:  - (id)initWithCoordinate:(CLLocationCoordinate2D)coord addressDictionary:(NSDictionary *)addressDictionary {
10:
11:       if ((self = [super initWithCoordinate:coord addressDictionary:addressDictionary])) {
12:            // NOTE: self.coordinate is now different from super.coordinate, since we re-declare this property in header,
13:            // self.coordinate and super.coordinate don't share same ivar anymore.
14:            self.coordinate = coord;
15:       }
16:       return self;
17:  }
18:  @end
AnnotationView.h:
1:  #import <MapKit/MapKit.h>
2:
3:  @interface AnnotationView : MKAnnotationView {
4:
5:  }
6:
7:  @property (nonatomic, assign) MKMapView *mapView;
8:
9:  @end
AnnotationView.m:
1:
2:  #import "AnnotationView.h"
3:  #import "CurrentLocationAnnotation.h"
4:
5:  @interface AnnotationView ()
6:  @property (nonatomic, assign) BOOL hasBuiltInDraggingSupport;
7:  @end
8:
9:  @implementation AnnotationView
10:  @synthesize hasBuiltInDraggingSupport;
11:  @synthesize mapView;
12:
13:  - (void)dealloc {
14:       [super dealloc];
15:  }
16:
17:  - (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
18:
19:       self.hasBuiltInDraggingSupport = [[MKAnnotationView class] instancesRespondToSelector:NSSelectorFromString(@"isDraggable")];
20:
21:       if (self.hasBuiltInDraggingSupport) {
22:            if ((self = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier])) {
23:                 [self performSelector:NSSelectorFromString(@"setDraggable:") withObject:[NSNumber numberWithBool:YES]];
24:            }
25:       }
26:       self.canShowCallout = YES;
27:
28:       return self;
29:  }
30:  @end
Step 6 - Now that we have our annotation view and placemark we can now add these to the map. I add the CurrentLocationAnnotation to the map in the locationManager:didUpdateToLocation:fromLocation method in the ProdjectNameViewController.m like so.
1:
2:  - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
3:  {
4:       [locationManager stopUpdatingLocation];
5:       if(currentLocation == nil) currentLocation = newLocation;
6:       else if (newLocation.horizontalAccuracy < currentLocation.horizontalAccuracy) currentLocation = newLocation;
7:
8:       [myMapView setRegion:MKCoordinateRegionMake(currentLocation.coordinate, MKCoordinateSpanMake(0.05f, 0.05f))];
9:       [myMapView setShowsUserLocation:NO];
10:
11:       CurrentLocationAnnotation *annotation = [[[CurrentLocationAnnotation alloc] initWithCoordinate:self.currentLocation.coordinate addressDictionary:nil] autorelease];
12:       annotation.title = @"Drag Me!";
13:       annotation.subtitle = @"Drag pin to get desired location..";
14:
15:       [myMapView addAnnotation:annotation];
16:  }
Now as soon as the application is loaded and we call the [locationManager startUpdatingLocation] this method is called and we drop a pin on the users current location.
Step 7 – Now we see where the AnnotationView class comes into play. In the Map View’s viewForAnnotation delegate method in the ProdjectNameViewController.m file we call for an AnnotationView which returns a draggable pin view.
1:  - (MKAnnotationView *)mapView:(MKMapView *)MapView viewForAnnotation:(id <MKAnnotation>)annotation
2:  {
3:       static NSString * const kPinAnnotationIdentifier = @"PinIdentifier";
4:       MKAnnotationView *draggablePinView = [MapView dequeueReusableAnnotationViewWithIdentifier:kPinAnnotationIdentifier];
5:
6:       if (draggablePinView) {
7:            draggablePinView.annotation = annotation;
8:       } else {
9:            draggablePinView = [[[AnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kPinAnnotationIdentifier] autorelease];
10:            if ([draggablePinView isKindOfClass:[AnnotationView class]]) {
11:                 ((AnnotationView *)draggablePinView).mapView = MapView;
12:            }
13:       }
14:       return draggablePinView;
15:  }
Step 8 – Once the users drags the pin, the didChangeDragState delegate method is called to update the latitude and longitude subtitle for the annotation.
1:  - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState
2:  {
3:       if (oldState == MKAnnotationViewDragStateDragging) {
4:            CurrentLocationAnnotation *annotation = (CurrentLocationAnnotation *)annotationView.annotation;
5:            annotation.subtitle = [NSString stringWithFormat:@"%f %f", annotation.coordinate.latitude, annotation.coordinate.longitude];
6:       }
7:  }
Conclusion – This is a very simple implementation of the draggable annotations that iOS4 has released but I feel that this will give you a base to creating a much more functional application with draggable pins. If there are any questions please feel free to comment. Project source is attached. Happy coding!
Source: iOS4DragDrop

Usefull Links

Downloads - cookbooksamples - Project Hosting on Google Code
iPhone Programming Tutorial – Local Notifications | Blancer.com Tutorials and projects
AppsAmuck iPhone Development Tutorials and Examples
The Daleisphere — iPhone App Development – Where to Start
Cocoa with Love: Tips & Tricks for conditional iOS3, iOS3.2 and iOS4 code
AVAudioPlayer volume problems - iPhone Dev SDK Forum
UNIX Tutorial One
How to target a specific iPhone version? - Stack Overflow
***OBJECTIVE-C WITH XCODE**: STANFORD ONLINE BOOKS
iPhone native apps icons: how to remove the glossy look. | Surgeworks Mobile
iPhone SDK – Get Current Touch Location | de
A-1 Technology Newsletter
C Tutorial
User Experience Coding How-To's
iOS4 Map Kit - Draggable Annotation Views | Trent Kocurek
PayPal X Developer Network: Community: PayPal Mobile XSpace
TheElements
UIKeyboardTypeNumberPad and the missing "return" key
PayPal X Developer Network: Community: PayPal Mobile XSpace
Cocoa Is My Girlfriend » Accessing The Cloud From Cocoa Touch
Using iPhone SDK MapKit Framework – A tutorial « The Spoken Word
100 Free Courses & Tutorials for Aspiring iPhone App Developers | Best Universities
[A-1 Technology Client Extranet] Sign in
In App Purchase Programming Guide: Introduction
erica's iphone-3.0-cookbook- at master - GitHub
Creating a Tabbar
Event-Driven XML Programming Guide: Parser Capabilities and Architecture
iPhone : warning: no ‘-renderInContext:’ method found – solution « Cocoa, Makin’ it Simple.
iphone - blend two uiimages - Stack Overflow
Java Operators Tutorial | Java Beginner