Wednesday, September 15, 2010

Processing Xml Webservices in IPhone

In this 2 part series I will show you how we can communicate to .NET XML web service(SOAP and REST types) using XCode. The detailed document is available for download HERE

Today I will discuss how to communicate to a SOAP based web service in your IPhone applications.We should keep in mind the fact that unlike .Net or Java where consuming web service is just a matter of a few clicks and the IDE's do the work of creating the proxy code for you,in XCode we have to manually do the web service configuration,making http/https calls and parsing the resulting Xml.

I would not be teach you creating .Net web services here but in my example I have a web service method named getPointsHistoryByCustomerID which takes an input value of a customer id,queries the database layer and returns the associated Customer profile as XML.

Refer to the PDF Document for details of the whole process along with the configuring/coding NSURL and NSURLConnection objects and using the delegates which are essential for request/response processing :

- (void)connection:(NSURLConnection *)connection didReceiveResponse:
(NSURLResponse *)response

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

-(void) connectionDidFinishLoading:(NSURLConnection *) connection

-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error

Monday, September 6, 2010

Core Data -1

When it comes to data management,we would generally use a file or a Sqlite Db to maintain persistent data.We would manually write the algorithm to save data/read to/from the persistent store into the memory and back.

Core data provides us a pre-packaged framework to create Models/Entities and API to persist
them on our devices.

When we create an Iphone App and check the coredata option the following 3 references are created in
the Application Delegate :

-NSManagedObjectModel *managedObjectModel;
- NSManagedObjectContext *managedObjectContext;
- NSPersistentStoreCoordinator *persistentStoreCoordinator;


There are 3 Layers in CoreDate architecture :
1. NSPeristantStoreCoordinator
    a.Responsibile for the direct link with the underlying physical store using NSURL
                    NSURL *storeUrl = [NSURL     fileURLWithPath:[[self applicationDocumentsDirectory]
                     stringByAppendingPathComponent: @"db.sqlite" ]];
                    
2.NSManagedObjectModel
        It contains the metadata for the model which in turn will contain the entities.
        The entity can be visualized as a class file which will replicate the database
        object in memory
   
3.NSManagedObjectContext
        The Managed Object Context(MOC) is used as a scratch pad.
        Objects are pulled through the stack into the
        MOC and then kept there while we change them. All inserts, deletes and
        updates to the set of objects in the MOC are held until we tell the MOC
        to save. At that point the MOC’s list of changes is pushed down through
        the stack, at each step translated closer to the eventual language of the
        POS(Persistant Object Store eg.File/SqlLite where it eventually becomes native
        (i.e. SQL statements for the SQLite POS) and sent to the persistent storage.
       
       
A.    Steps involved in creating a PersistentStoreCoordinator

    -(NSPersistentStoreCorordinator *) persistentStoreCoordinator
    {
        if(!persistentStoreCoordinator) return persistentStoreCoordinator;

        NSURL *storeUrl =[NSURL fileURLWithPath:[[self applicationDocumentDirectory] 
                stringByAppendingPathComponent:@"db.sqlite"]];

        NSError *error=nil;
        persistentStoreCoordinator =[[NSPersistentStoreCorordinator alloc]
                        initWithObjectModel:[self managedObjectModel]];

        if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                    configuration:nil
                    URL:storeUrl
                    options:nil
                    error:&error])
        {
            //handle errors
        }

        return persistentStoreCoordinator;
    }

    (NSString *)applicationDocumentsDirectory {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *basePath = nil;
        if([paths count] > 0)
        {
            basePath = [paths objectAtIndex:0];
        }
        return basePath;
    }

B.     Steps involved in creating the ManagedObjectModel which will store all our entities
    -(NSManagedObjectModel *) managedObjectModel
    {
        if(managedObjectModel!=nil)
            return managedObjectModel;
       
        //This will create one MOM for all model files in our application
        managedObjectModel=[[NSManagedObjectModel mergedModelFromBundles:nil] retain];
       
        return managedObjectModel;
    }
   




C.    Steps involved in creating the ManagedObjectContext
    i.  Get the persistent store coordinator
    ii. Configure the ManagedObjectContext
   
    - (NSManagedObjectContext *) managedObjectContext
    {
        if (managedObjectContext != nil)    
            return managedObjectContext;
       
        NSPersistentStoreCoordinator *coordinator=[self persistentStoreCoordinator];
        if(coordinator != nil)
        {   
            managedObjectContext=[[NSManagedObjectContext alloc] init];
            [managedObjectContext setPersistentCoordinator:coordinator];
        }
        return     managedObjectContext;
    }
  

Wednesday, March 24, 2010

Location tracking in IPhone

IPhone provides you the ability to get your location and relies on cell tower triangulation as well as a built in GPS.
In this tutorial I will demonstrate you how to find you Location using a small IPhone App.
You can Integrate a MKMapKit/MKMapView to enhance this to make the output more graphical.
I will try to provide a small demo on that if I get time later.

Add the Core Location framework to your project to use the location data.
Add a few UILabel controls for displaying the longitude and latitude.For updating the labels we will need the associated
IBOutlets to these labels.If you are not familiar with IBAction/Outlets then refer to the apple documentation.
The sample code is as below


#import "<UIKit/UIKit.h>"

@interface MyLocationViewController : UIViewController {
  IBOutlet UILabel *latitude;
  IBOutlet UILabel *longitude;
}

@end


We will use the CLLocationManager class to send updates to a delegate when our the location changes.
The delegate associated to this class is CLLocationManagerDelegate so our view controller should implement
this delegate.

#import "<UIKit/UIKit.h>"
#import "<CoreLocation/CoreLocation.h>"

@interface MyLocationViewController : UIViewController < CLLocationManagerDelegate >
  {
  CLLocationManager *locationManager;
  IBOutlet UILabel *latitude;
  IBOutlet UILabel *longitude;
}

@end

In the viewDidLoad of the Viewcontroller configure the CLLocationManager settings like distanceFilter,desiredAccuracy etc and then call the startUpdatingLocation function of the CLLocationManager to get the delegate working.

- (void)viewDidLoad {
  [super viewDidLoad];
  locationManager = [[CLLocationManager alloc] init];
  locationManager.delegate = self;
  locationManager.distanceFilter = kCLDistanceFilterNone;
  locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
  [locationManager startUpdatingLocation];
}

From the  delegate protocol implement the following delegate in your viewController

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation


The full body of the implementation will be

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
  int degrees = newLocation.coordinate.latitude;
  double decimal = fabs(newLocation.coordinate.latitude - degrees);
  int minutes = decimal * 60;
  double seconds = decimal * 3600 - minutes * 60;
  NSString *lat = [NSString stringWithFormat:@"%d° %d' %1.4f\"",
                   degrees, minutes, seconds];
  latitude.text = lat;
  degrees = newLocation.coordinate.longitude;
  decimal = fabs(newLocation.coordinate.longitude - degrees);
  minutes = decimal * 60;
  seconds = decimal * 3600 - minutes * 60;
  NSString *longt = [NSString stringWithFormat:@"%d° %d' %1.4f\"",
                     degrees, minutes, seconds];
  longitude.text = longt;
}
Here we take the location and turn the degrees into degrees, minutes, and seconds then display the value in the correct label.
For the mathematical calculation remember Each 1 degree= 60 minutes = 3600 seconds. 

Getting a hang of delegate feature in IPhone is the core to this end of programming so master that first and then get into some serious IPhone programming.