Wednesday, January 16, 2013

iOS Development From The Frontlines Core Location in iOS: A Tutorial

Core Location in iOS: A Tutorial



Developing iOS apps that can take advantage of the built-in GPS unit is a great way to add a new dimension to the user experience. You can quickly make your apps location-aware (and able to find the current latitude/longitude coordinates) with minimal effort. This tutorial will walk through the steps involved in finding a device’s current position.
In iOS, you can find the current lat/lng by making a request to the Core Location component to start looking up location information. This works via a series of delegate messages passed to our application when Core Location starts updating. By default, the location hardware in our device is usually turned off (or otherwise in an idle state) so as not to needlessly drain power. In a nutshell we need to:
  1. #import the correct Core Location header file
  2. Link against the Core Location framework
  3. Implement two delegate methods to receive information from Core Location
  4. Tell Core Location to start sending us updates
  5. Properly shut down Core Location when we don’t need it anymore.

Getting Started

Since we’re going to be using Core Location with our iOS app, we need to add the header file (CoreLocation/CoreLocation.h) to our prefix header (usually with the extension .pch). In this prefix header, locate the #ifdef __OBJC__ line:
#ifdef __OBJC__
    #import 
    #import 
    #import  // added for Core Location
#endif
If you have a larger project and are only using Core Location in a few places, you could alternatively just add the #import line to the files where you actually need it. In our simple example, we’ll stick with the prefix file.
Next, we need to add the Core Location framework to our project’s link phase. In Xcode, click on the project’s name at the top of the project navigator view. In the Linked Frameworks and Libraries section, click the “+” icon to add a new framework. Find the Core Location.framework entry, and add it. When you next link your project, the framework will be automatically included.


Setting up the Delegate

The begin setting up our class as a delegate, the first step is to locate the class where we want to receive Core Location messages. Then, we need to set that class up as a CLLocationManagerDelegate. You can do this by adding to the @interface definition line.
Next, in the implementation file, we need to add two delegate methods:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
This method will be called when Core Location has new location data for us to process. We receive these messages both when we have better accuracy for a current location, or the device has moved. These messages can also come in quickly one after the other, or as a trickle.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
If Core Location needs to report a failure of some kind, this method will be called. We need to properly handle these. Note that this method is technically optional, but it’s best to get into the habit of handling these messages.
Next, we also need a way to store where we currently are located. Since there’s no guarantee of when we’ll be told of our location, we need to store this information for the times when we need to reference it. We also need to keep track of our Core Location manager instance. So, be sure to add the following to your class’ @interface definition:
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *currentLocation;
And, in the implementation file, the corresponding synthesize methods:
@synthesize locationManager, currentLocation;

Receiving Messages

Now that the setup is out of the way, it’s on to the fun stuff. First, let’s implement the didUpdateToLocation method. I’ll paste the entirety here and then we’ll step through it:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    self.currentLocation = newLocation;
 
    if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}
First, note that we’re saving the currentLocation. Again, since we don’t know when we’re going to be given an update to our location, we need to keep this around for whenever we might need it in the future.
Next, we check the included accuracy against a pre-set expectation. Each time we’re given a newLocation, we’re given an estimation on how accurate it is. This float is in meters, and usually starts out as pretty inaccurate (remember that when we first start requesting location updates, Core Location needs to determine the device’s location, which can take time).
You’ll notice in the Maps app on your iPhone that a blue circle is initially drawn around the point marking your location. That blue circle’s radius is determined by this horizontalAccuracy number. If you’re going to be showing a point on a map for the user’s current location, you may want to consider adding a similar “accuracy circle”.
The reason why we’re checking the provided accuracy against a pre-set expectation is that we don’t want to leave Core Location running for any longer than we absolutely need it to. It drains the battery life of the device when it has to communicate with GPS satellites or power up the radio for location triangulation, so we want to turn it back off again as soon as we have a good-enough position. In the example above, a position +/- 100m is plenty accurate for us. To stop Core Location from sending us updates (and thus allowing it to go back into an idle state), we send our locationManager the stopUpdatingLocation message.
Lastly, we need to implement the didFailWithError method. Here it is:
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if(error.code == kCLErrorDenied) {
        [locationManager stopUpdatingLocation];
    } else if(error.code == kCLErrorLocationUnknown) {
        // retry
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error retrieving location"
                              message:[error description]
                              delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
}
When handling errors from Core Location, we need to worry about two special cases. The first is when the user specifically denies our app access to finding its position. If that occurs, we want to immediately stop trying to update by sending the stopUpdatingLocation message.
The second special case is when we’re given a kCLErrorLocationUnknown error. This can occur when Core Location is first starting up and isn’t able to immediately determine its position, or even make a guess as to where it is. If we get this message, its best to ignore it and to keep trying to update our location.
In other cases, we may want to alert the user to a problem with getting a location. According to the Core Location docs, this might occur when the device is near a particularly strong magnetic field. In this example, we’re showing the user a problem but still retrying. You will need to determine for your own app whether you want to stop trying to get location updates at this point or to keep retrying.

Requesting Updates

After the delegate has been implemented, it’s time to actually setup Core Location and request location updates. To setup Core Location, you’ll want to do the following:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
This sets up a new CLLocationManager instance and saves a pointer to it in a class variable. We next set our current class up as the delegate to receive CLLocationManagerDelegate messages. And finally, we tell Core Location to start figuring out our position.
In my example app, I’ve placed all of my Core Location-related code in a single view controller’s class as I only need this information in one section of my app. Thus, I placed the above three lines in my viewDidLoad method, which is called after the view has been loaded, but before it’s being shown to the user. This could occur right when the app opens up (if loaded from the XIB file), but it could also occur at another point in the app, such as after a low-memory condition and the view had been previously unloaded.
Since I put this setup code in the viewDidLoad method, I also need to remember to tell Core Location to stop updating should my view get unloaded. Thus, I placed the following line in my viewDidUnload method:
[locationManager stopUpdatingLocation];
It’s important to remember to tell Core Location to stop sending messages to the delegate before the delegate could be freed, which could cause Core Location to attempt to send messages to a freed/nil object (which would cause a crash).
And that’s all there is to it! Implementing Core Location is an easy thing to implement and can add an interesting new dimension to your iOS apps. Be sure to post in the comments if you found this interesting or have questions.

Wednesday, November 7, 2012

UIView into UIImage. i.e. screen snapshot of a view

@interface UIView(Extended) 

- (UIImage *) imageByRenderingView;

@end


@implementation UIView(Extended)


- (UIImage *)imageByRenderingView
{   
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

@end
 
 
Just Call:- 
 
UIImage *currImage = [self.view imageByRenderingView];
 

 
You can split your UIImage in two by using this code:
CGImageRef topOfImageCG =
         CGImageCreateWithImageInRect(currImage.CGImage,
                                      CGRectMake(0,
                                                 0,
                                                 currImage.size.width,
                                                 currImage.size.height / 2.0));

UIImage *topOfImage = [UIImage imageWithCGImage:topOfImageCG];

CGImageRelease(topOfImageCG);
  

Wednesday, October 31, 2012

Touch Began for particular CGRect and Rotating Image with finger moved


// sample code inside Touchesbegan method
CGRect tempRect = CGRectMake(x, y, width, height);
if (CGRectContainsPoint(tempRect, touchlocation)) 
{
    // do some thing
}
- (void)viewWillAppear:(BOOL)animated
{
    imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mycard_back_dark_bg.png"]];
   imageView2.frame=self.imageView.frame;
    
    imageView2.bounds = self.imageView.bounds;
    [self.view addSubview:self.imageView2];
    [self.view sendSubviewToBack:imageView2];
    
    UIImage *image = [UIImage imageNamed:@"mycard_back_dark_bg.png"];
    
    UIImageOrientation flippedOrientation = UIImageOrientationUpMirrored;
    
    
    
    switch (image.imageOrientation)
    {
        case UIImageOrientationUp:
                                   break;
            
        case UIImageOrientationDown:
                                    flippedOrientation = UIImageOrientationDownMirrored;
                                    break;
        case UIImageOrientationLeft:    
                                    break;
        case UIImageOrientationRight:
                                    break;
        case UIImageOrientationUpMirrored:
                                    break;
        case UIImageOrientationDownMirrored:
                                    break;
        case UIImageOrientationLeftMirrored:
                                    break;
        case UIImageOrientationRightMirrored:
                                    break;
            
           
    }
    UIImage * flippedImage = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:flippedOrientation];
    
    self.imageView2.image=flippedImage;
    
    UILabel *cardNo= [[UILabel alloc] initWithFrame:CGRectMake(self.imageView.frame.origin.x+5, self.imageView.frame.origin.y+10, self.imageView.frame.size.width-30, self.imageView.frame.size.height/4)];
    
    [cardNo setText:@"5081 5988 1045 2318"];
    [cardNo setTextColor:[UIColor whiteColor]];
    [cardNo setBackgroundColor:[UIColor clearColor]];
    
    [self.imageView addSubview:cardNo];
    
   
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    
    
UITouch *touch = [touches anyObject];
CGPoint origin = [self.imageView center];
    
    // sample code inside Touchesbegan method
    CGRect tempRect = CGRectMake(0, 0, 320, 200);
    if (CGRectContainsPoint(tempRect, [touch locationInView:self.view]))
    {
        // do some thing
        CGFloat angle = angleBetweenLinesInRadians(origin, [touch previousLocationInView:self.view], origin, [touch locationInView:self.view]);
        
        // NSLog(@"angle %2f",angle);
        i=i+angle;
        
        // NSLog(@"value of i %f",i);
        self.imageView.layer.doubleSided=FALSE;
        
        //self.imageView2.hidden = YES;
        self.imageView.layer.transform=CATransform3DMakeRotation(i, 0.0, 0.1, 0.0);
        
        self.imageView2.layer.transform=CATransform3DMakeRotation(i, 0.0, 0.1, 0.0);
        
        //  NSLog(@"position.z %f",self.imageView.layer.zPosition);
        // NSLog(@"position.y %f",self.imageView.layer.position.y);
        
        CALayer* layer = [self.imageView.layer presentationLayer];
        float currentAngle = [[layer valueForKeyPath:@"transform.rotation.z"] floatValue];
        NSLog(@"currentAngle %f",currentAngle);
        
        CALayer* layer2 = [self.imageView2.layer presentationLayer];
        float currentAngle2 = [[layer2 valueForKeyPath:@"transform.rotation.z"] floatValue];
        NSLog(@"currentAngle2 %f",currentAngle2);
    }
    
    
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    CALayer* layer = [self.imageView.layer presentationLayer];
    float currentAngle = [[layer valueForKeyPath:@"transform.rotation.z"] floatValue];
    NSLog(@"currentAngle %f",currentAngle);
    
    if (currentAngle==0) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.75];
        [UIView setAnimationDelay:0.0];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
         
         self.imageView.layer.transform=CATransform3DMakeRotation(0, 0.0, 0.1, 0.0);
         self.imageView2.layer.transform=CATransform3DMakeRotation(0, 0.0, 0.1, 0.0);
        
        [UIView commitAnimations];
        
        i=0;
        
    }else {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.75];
        [UIView setAnimationDelay:0.0];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        self.imageView.layer.transform=CATransform3DMakeRotation(3.14, 0.0, 0.1, 0.0);
        self.imageView2.layer.transform=CATransform3DMakeRotation(3.14, 0.0, 0.1, 0.0);
        
        [UIView commitAnimations];
        
       i=3.14;
    }
}
static inline CGFloat angleBetweenLinesInRadians(CGPoint line1Start, CGPoint line1End, CGPoint line2Start, CGPoint line2End) {
    
    CGFloat a = line1End.x - line1Start.x;
    CGFloat b = line1End.y - line1Start.y;
    CGFloat c = line2End.x - line2Start.x;
    CGFloat d = line2End.y - line2Start.y;
    
    CGFloat line1Slope = (line1End.y - line1Start.y) / (line1End.x - line1Start.x);
    CGFloat line2Slope = (line2End.y - line2Start.y) / (line2End.x - line2Start.x);
    
    CGFloat degs = acosf(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));
    
    
    return (line2Slope > line1Slope) ? degs : -degs;    
}

Friday, June 1, 2012

MapKit and the MKMapView Class

Working with Maps on the iPhone with MapKit and the MKMapView Class

In the preceding chapters we spent some time looking at handling raw geographical location information in the form of longitude, latitude and altitude data. The next step is to learn about the presentation of location information to the user in the form of maps and satellite images. The goal of this chapter, therefore, is provide an overview of the steps necessary to present the iPhone iOS 5 application user with location, map and satellite imagery using the MapKit framework and, in particular, the MKMapView class.

Contents

[hide]













[edit] About the MapKit Framework

The MapKit Framework is based on the Google Earth and Google Maps data and APIs and provides iPhone developers with a simple mechanism for integrating detailed and interactive mapping capabilities into any application.
The core element of the MapKit framework from the point of view of the app developer is the MKMapView class. This class is a subclass of UIView and provides a canvas onto which map and satellite information may be presented to the user. Information may be presented in map, satellite or hybrid (whereby the map is superimposed onto the satellite image) form. The displayed geographical region may be changed manually by the user via a process of pinching stretching and panning gestures, or programmatically from within the application code via methods calls and property manipulation on the MkMapView instance. The current location of the device may also be displayed and tracked on the map view.
The MapKit framework also includes support for adding annotations to a map. This takes the form of a pin or custom image, title and subview that may be used to mark specific locations on a map.
Implementation of the MKMapViewDelegate protocol allows an application to receive notifications of events relating to the map view such as a change in either the location of the user or region of the map displayed or the failure of the device to identify the user’s current location or to download map data.

[edit] Understanding Map Regions

The area of the map that is currently displayed to the user is referred to as the region. This is defined in terms of a center location (declared by longitude and latitude) and span of the surrounding area to be displayed. Adjusting the span has the effect of zooming in and out of the map relative to the specified center location. The region’s span may be specified using either distance (in meters) or coordinate based degrees. When using degrees, one degree of latitude is equivalent to 111 km. Latitude, however, varies depending on the longitudinal distance from the equator. Given this complexity, the map view tutorial in this chapter will declare the span in terms of distance.

[edit] About the iPhone MKMapView Tutorial

The objective of this tutorial is to develop an iPhone application designed to display a map with a marker indicating the user’s current location. Buttons located in a navigation bar are provided to allow the user to zoom in on the current location and to toggle between map and satellite views. Through the implementation of the MKMapViewDelegate protocol the map will update as the user’s location changes so that the current location marker is always the center point of the displayed map region. Finally, a basic annotation will be implemented to mark a specific location on the map with a pin and title.

[edit] Creating the iPhone Map Tutorial

Begin by launching Xcode and creating a new iOS iPhone project named mapSample using the Single View Application template.

[edit] Adding the MapKit Framework to the Xcode Project

Since we will be making use of the MapKit framework during this tutorial the first step is to add the framework to the project. To achieve this, select the Build Phases tab on the mapSample summary panel and unfold the Link Binary with Libraries section. Click on the ‘+’ button, locate the MapKit.framework entry from the resulting list and click Add.

[edit] Declaring an Outlet for the MapView

Clearly since we plan on working with an MKMapView object in our iPhone iOS 5 application it will be necessary to declare an outlet for this object. Later in the tutorial we will add code to update the map based on changes to the user’s location. To do this it will also be necessary to implement the MKMapViewDelegate protocol within our view controller class. The application is also going to require a toolbar which we will reference via an outlet named toolBar. Finally, the code will require that the <MapKit/MapKit.h> file be imported. All these code changes may be implemented in the mapSampleViewController.h file as follows:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface mapSampleViewController : UIViewController {
    <MKMapViewDelegate>
{
        MKMapView *mapView;
        UIToolBar *toolBar;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
@property (strong, nonatomic) IBOutlet UIToolBar *toolBar;
@end
Having declared the outlet, add the corresponding synthesize directive to the mapSampleViewController.m file:
#import "mapSampleViewController.h"
@implementation mapSampleViewController
@synthesize mapView, toolBar;
.
.
@end

[edit]

Creating the MKMapView and Connecting the Outlet

The next step is to create an instance of the MKMapView class we will be using in our application and to add a toolbar instance to the user interface. Begin by selecting the mapSampleViewController.xib file so that the Interface Builder panel appears. Drag a Tool Bar from the Object Library and place it at the bottom of the view canvas. Next, drag and drop a Map View object onto the canvas and resize and position it so that it takes up the remaining space in the view above the toolbar:


Figure 48-1
If present, select the button in the toolbar labeled “Item” and press the Delete key on the keyboard to remove it from the design. Connect the mapView outlet to the object by Ctrl-clicking on the File’s Owner object and dragging the resulting line to the Map View object. Release the line and select mapView from the menu. Repeat these steps to map the toolbar outlet to the tool bar object.
Perform a test run of the application’s progress so far by clicking on the Run button in the Xcode toolbar. The application should run in the iOS simulator as illustrated in Figure 48-2:


Figure 48-2

[edit]

Adding the Tool Bar Items

Next, the two buttons need to be added to the navigation bar. This code will be placed in the viewDidLoad method located in the mapSampleViewController.m file. Now is also a good time to configure the mapView to display the user’s current location by setting the showsUserLocation property:
- (void)viewDidLoad
{
    [super viewDidLoad];
    mapView.showsUserLocation = YES;
    UIBarButtonItem *zoomButton = 
        [[UIBarButtonItem alloc]
         initWithTitle: @"Zoom"
         style:UIBarButtonItemStylePlain
         target: self
         action:@selector(zoomIn:)];
    UIBarButtonItem *typeButton = 
        [[UIBarButtonItem alloc]
        initWithTitle: @"Type"
        style:UIBarButtonItemStylePlain
        target: self
        action:@selector(changeMapType:)];
    NSArray *buttons = [[NSArray alloc] 
         initWithObjects:zoomButton, typeButton, nil];
    toolBar.items = buttons;
}
First the mapView is configured to show the user location (which appears on the map as a blue translucent ball):
mapView.showsUserLocation = YES;
Next two tool bar button items labeled “Zoom” and “Type” are created and configured to call the zoomIn and changeMapType methods respectively. These button are then placed in an array and the array assigned to the items property of the toolbar object in order to make them visible to the user.

[edit] Changing the MapView Region

When the Zoom button is tapped by the user the map view region needs to be changed so that the user’s current location is set as the center location and the region span needs to be changed to 50 meters (analogous to zooming in to the map region). The code to implement this belongs in the zoomIn method located in the mapSampleViewController.m file:
- (void)zoomIn: (id)sender
{
    MKUserLocation *userLocation = mapView.userLocation;
    MKCoordinateRegion region =
       MKCoordinateRegionMakeWithDistance (
          userLocation.location.coordinate, 50, 50);
    [mapView setRegion:region animated:NO];
}
This method performs some very simple operations in order to achieve the desired effect in the mapView object. Firstly, the user’s current location is ascertained by accessing the userLocation property of the map view object. This is stored in the form of an MKUserLocation object which, in turn, contains the coordinates of the user. Next, the MKCoordinateRegionMakeWithDistance function is called in order to generate an MKCoordinateRegion object consisting of the user’s location coordinates and a span that stretches 50 meters both to the North and South of the current location. Finally, this region object is passed through to the setRegion method of the mapView object.
Now that the Zoom functionality has been implemented it is time to configure the map type switching feature of the application.

[edit] Changing the Map Type

The map type of a map view is controlled by the object’s mapType property. Supported values for this property are MKMapTypeStandard, MKMapTypeSatellite and MKMapTypeHybrid. For the purposes of this example application the map will switch between standard and satellite modes. Within the mapSampleViewController.m file add the changeMapType action method connected to the Type button as follows:
- (void) changeMapType: (id)sender
{
    if (mapView.mapType == MKMapTypeStandard)
        mapView.mapType = MKMapTypeSatellite;
    else
        mapView.mapType = MKMapTypeStandard;
} 
This very simple method simply toggles between the two map types when the button is tapped by the user.

[edit] Testing the iPhone MapView Application

Now that more functionality has been implemented, it is a good time to build and run the application again so click on the Xcode Run button to load the application into the iOS iPhone Simulator. Once the application has loaded, a blue dot should appear over Northern California. Since the application is running in the simulator environment the location information is simulated to match the coordinates of Apple’s headquarters in Cupertino, CA. Select the Type button to display the satellite view and then zoom in to get a better look at the company’s parking lot:


Figure 48-3

To get real location information, load the application onto an iPhone device (details of which can be found in the Testing iOS 5 Apps on the iPhone – Developer Certificates and Provisioning Profiles chapter of this book).

[edit] Updating the Map View based on User Movement

Assuming that you installed the application on a physical iPhone device and went somewhere with the device in your possession you may have noticed that the map did not update as your location changed and that the blue dot marking your current location eventually went off the screen (also assuming, of course, that you had zoomed in).
In order to configure the application so that the map automatically tracks the movements of the user the first step is to make sure the application is notified when the location changes. At the start of this tutorial the view controller was declared as conforming to the MKMapViewDelegate delegate protocol. One of the methods that comprise this protocol is the didUpdateUserLocation method. When implemented, this method is called by the map view object whenever the location of the device changes. We must, therefore, first specify that the mapSampleViewContoller class is the delegate for the mapView object, which can be performed by adding the following line to the viewDidLoad method located in the mapSampleViewController.m file:
mapView.delegate = self; 
The next task involves the implementation of the didUpdateUserLocation method in the mapSampleViewController.m file:
- (void)mapView:(MKMapView *)mapView 
didUpdateUserLocation:
(MKUserLocation *)userLocation
{
    self.mapView.centerCoordinate = 
          userLocation.location.coordinate;
} 
The delegate method is passed as an argument an MKUserLocation object containing the current location coordinates of the user. This value is simply assigned to the center coordinate property of the mapView object such that the current location remains at the center of the region. When the application is now installed and run on a device the current location will no longer move outside the displayed region as the device location changes.

[edit] Adding Basic Annotations to a Map View

The last task in this tutorial is to add an annotation at a specific location on the map view. For the purposes of this example, we will add a standard annotation (represented by default by a red pin) at the coordinates of Microsoft’s headquarters in Redmond, Washington. Although this is a very simple example it is important to keep in mind that annotations may also be used to perform more advanced tasks such as displaying custom images and multiple annotations on a single map.
The annotation in this example will also display a title and subtitle when selected by the user. In order to create a basic annotation it is necessary to create a CLLocationCoordinate2D object containing the coordinates at which the annotation is to appear. An MKPointAnnotation object is then created and assigned the coordinate object, title and subtitle strings. Finally the addAnnotation method of the map view object is called to add the annotation to the map. The code fragment for these steps is as follows:
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = 47.640071;
annotationCoord.longitude = -122.129598;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = @"Microsoft";
annotationPoint.subtitle = @"Microsoft's headquarters";
[mapView addAnnotation:annotationPoint]; 
Add this code to the end of the viewDidLoad method and build and run the application. The map should now appear with a red pin located at the designated location. Tapping the pin will display the title and subtitle:


Figure 48-4