By A Beginner

Every Expert Was Once A Beginner

iOS: To Draw Poly line on apple maps to show directions from Source to Destination in your app. — January 24, 2015

iOS: To Draw Poly line on apple maps to show directions from Source to Destination in your app.

Making use of the mapkit and core location frameworks we can easily draw a poly line indicating the direction from the given source lat,long to destination lat,long . We can set the source and the destination point coordinates  and create the source and destination map items by using the below code.

//To set the source place mark
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.333144, -122.021509) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

//To create the source map items
 MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];

Similarly we use same to set the destination place mark and map item using,

  MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.331741, -122.030333) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

 MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];

We can now get the direction between the source and destination bu making the MKDirectionRequest  as shown below.

MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
request.requestsAlternateRoutes = YES; //for alternate routes from src to destination.
[request setTransportType:MKDirectionsTransportTypeAutomobile];

The response of the MKDirectionRequest contains the direction details .

MKDirections *direction = [[MKDirections alloc] initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
     NSLog(@"response = %@",response);  //Contains the calculated direction information from source to destination.

}];

Now we have the directions we make use of the below map view delegate method to draw the poly line from source to destination points on the map.

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay {
     if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineView* aView = [[MKPolylineView alloc]initWithPolyline:(MKPolyline*)overlay] ;
        aView.strokeColor = [[UIColor colorWithRed:69.0/255.0 green:147.0/255.0 blue:240.0/255.0 alpha:1.0] colorWithAlphaComponent:1];
        aView.lineWidth = 10;
        return aView;
     }
     returne nil;
}

We can also make use of the  viewForLocation: map view delegate method to change the appearance of the map pins of the source and the destination points on the map.

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotationPoint{
     static NSString *annotationIdentifier = @"annotationIdentifier";
     MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotationPoint reuseIdentifier:annotationIdentifier];
      if ([[annotationPoint title] isEqualToString:@"Source"]) {
            pinView.pinColor = MKPinAnnotationColorRed;
      }else{
            pinView.pinColor = MKPinAnnotationColorGreen;
      }
       return pinView;
}

Download the sample code here: GitHub Link

iOS : Get Current Location Latitude and Longitude —

iOS : Get Current Location Latitude and Longitude

To get a current location latitude and longitude values using Core Location framework.

1. Include the core location framework in to your project by going to Link Binaries With Libraries in your projects Build Phases.

2. Then make your view controller to conform to CLLocationManagerDelegate in viewcontroller.h file as below.

#import <CoreLocation/CoreLocation.h>
@interface TLViewController : UIViewController<CLLocationManagerDelegate>{
      CLLocationManager *locationManager;
}

3. Initialize the location manager object and call the method CurrentLocationIdentifier as below.

locationManager = [[CLLocationManager alloc] init];
 [self CurrentLocationIdentifier]; // method prints the current location latitude and longitude values.
-(void)CurrentLocationIdentifier{
      //---- For getting current gps location
      locationManager = [CLLocationManager new];
      locationManager.delegate = self;
      locationManager.desiredAccuracy = kCLLocationAccuracyBest;
      [locationManager startUpdatingLocation];
}

4. The location manager delegates fetches the locations latitude and longitude values as and when it is  updated and prints it in the log.

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    if (currentLocation != nil) {
         NSLog(@"%.8f-%.8f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude);
    }
}

Download X-Code Project Here!

iOS: Core Data Framework — January 20, 2015

iOS: Core Data Framework

Core Data is a framework by apple which deals with the model layer of the Model-View-Controller design pattern in the application. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It provides the optimized solution for saving the objects in to the memory and fetching it from the storage when needed. Core Data is used as the in memory store for the application as it provides generalized and automated solutions to common tasks associated with object life-cycle and object graph management, including persistence on disk.

It takes advantage of information provided in the model and runtime features not typically employed in application-level code. Moreover, in addition to providing excellent security and error-handling, it offers best memory scalability of any competing solution.

Core Data Framework is made up of core data stack . It is the ordered collection of objects from a managed object context, through a persistent object store coordinator, to a persistent store or collection of persistent stores. A stack is effectively defined by a persistent store coordinator ,there is one and only one per stack. Creating a new persistent store coordinator implies creating a new stack.

CoreData1

Fig:1.0_ Core Data Stack Contents.

In Core Data the NSManagedObjectModel, the NSPersistentStoreCoordinator, and the NSManagedObjectContext all of these on the stack work together to allow a program to retrieve and store NSManagedObject instances. In most situations, the program will access the NSManagedObjectContext only once the stack has been created. It is possible to access the other components of the stack, but it is rarely necessary.

Managed Object : Model objects that tie into in the Core Data framework are known as managed objects .It is an instance of NSManagedObject or a subclass of NSManagedObject. After creation it should be registered with a managed object context.

Managed Object Context : When the objects are fetched from the persistent store, they are brought in to managed object context where they form an object graph (or collection of object graphs). You can then modify those objects however you like. Unless you actually save those changes, however, the persistent store remains unaltered. It is an instance of NSManagedObjectContext. An NSManagedObjectContext object represents a single “object space” or scratch pad in an application. The context is a powerful object with a central role in the life-cycle of managed objects, with responsibilities from life-cycle management (including faulting) to validation, inverse relationship handling, and undo/redo.

Managed Object Model : An object that is an instance of NSManagedObjectModel. An NSManagedObjectModel object describes a schema, a collection of entities (data models) that you use in your application. It uses a private internal store to maintain its properties and implements all the basic behavior required of a managed object.

Img1Fig:1.1_Managed Object Model

Persistent Object Store Coordinator : An object that is an instance of NSPersistentStoreCoordinator. A coordinator associates persistent stores and a configuration of a managed object model and presents a facade to managed object contexts such that a group of persistent stores appears as a single aggregate store.

Persistent Object Store : A repository in which objects may be stored. A repository is typically a file, which may be XML, binary, or a SQL database. The store format is transparent to the application. Core Data also provides an in-memory store that lasts no longer than the lifetime of a process.

img2

Fig:1.2_Advance Persistence Stack

About Persistent Documents :

We can create and configure the persistence stack programmatically. In many cases, when we simply want to create a document-based application that is able to read and write files. The NSPersistentDocument class is a subclass of NSDocument that is designed to let you easily take advantage of the Core Data framework. By default, an NSPersistentDocument instance creates its own ready-to-use persistence stack, including a managed object context and a single persistent object store. There is in this case a one-to-one mapping between a document and an external data store.

The NSPersistentDocument class provides methods to access the document’s managed object context and provides implementations of the standard NSDocument methods to read and write files that use the Core Data framework. By default you do not have to write any additional code to handle object persistence. A persistent document’s undo functionality is integrated with the managed object context.

To Fetch Stored Data :

To retrieve data from a persistent store like a database SELECT operation. The result of a fetch is the creation of a collection of managed objects that are registered with the managed object context used to issue the request.

Fetch Request : An instance of NSFetchRequest that specifies an entity and optionally a set of constraints, represented by a NSPredicate object , and an array of sort descriptors (instances of NSSortDescriptor). These are similar to the table name, WHERE clause, and ORDER BY clauses of a database SELECT statement respectively. A fetch request is executed by being sent to a managed object context.

fetch_request_2x

Fig:1.3_Demonstrating Fetch Request

To Insert Data :

The process of adding a managed object to a managed object context so that the object becomes part of the object graph and will be committed to a persistent store. Typically “insertion” refers only to the initial creation of a managed object. Thereafter, managed objects retrieved from a persistent store are considered as being fetched.

A managed object must be inserted into a managed object context before it is considered part of the object graph. A managed object context is responsible for observing changes to managed objects (for the purposes of undo support and maintaining the integrity of the object graph), and can only do so if new objects are inserted.

Features :

  • Core Data provides built-in management of undo and redo beyond basic text editing.

  • Core Data manages change propagation, including maintaining the consistency of relationships among objects.

  • It supports faulting which helps in reducing the memory over head of the program by lazily loading objects and also supports copy-on-write data sharing .

  • Core Data’s managed objects extend the standard key-value coding (KVC) validation methods that ensure that individual values lie within acceptable ranges so that combinations of values make sense.

  • In addition to synthesizing key-value coding (KVC) and key-value observing (KVO) compliant accessor methods for attributes, Core Data synthesizes the appropriate collection accessors for to-many relationships.

  • It also provides an option to integrate the application’s controller layer to support user interface synchronization, by providing the NSFetchedResultsController object on iOS, and integrates with Cocoa Bindings on OS X.

  • Automatic support for storing objects in external data repositories.

Conclusion :

Using core data reduces the amount of the code to be written to support the model layer of the application as it provides the various features to manage the data objects. It also eliminates the optimization of the code for managing data in the application as the framework has been highly optimized over several releases so far.

It takes advantage of information provided in the model and runtime features not typically employed in application-level code. Moreover, in addition to providing excellent security and error-handling, it offers best memory scalability of any competing solution.

Core Data is not a relational database or a relational database management system (RDBMS). It provides an infrastructure for change management and for saving objects to and retrieving them from storage thus behaving as an in memory store of the application. It uses the SQLITE as one of its persistent store .

References:

  1. https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html#//apple_ref/doc/uid/TP30001200-SW1

  2. https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650-TP1

  3. https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdGlossary.html#//apple_ref/doc/uid/TP40001651-TP1

iOS:To seprate group of ANAGRAMS in an array — January 17, 2015

iOS:To seprate group of ANAGRAMS in an array

Here is the code for grouping and printing the set of anagrams in an array.If any better solutions please Comment.


- (void)viewDidLoad
 {
 [super viewDidLoad];
 //self.view.backgroundColor=[UIColor blueColor];
 // Do any additional setup after loading the view, typically from a nib.
 NSString *tmpStr1;
 NSString *tmpStr2;
 NSMutableArray *newArr=[[NSMutableArray alloc] init];
 BOOL Var=NO;
 int i,j;
 NSArray *arr1=[[NSArray alloc] initWithObjects:@"star",
 @"rats",
 @"arts",
 @"car",
 @"rac",
 @"arc",
 @"abcde",
 @"bcdea",
 @"cdeab", nil];
 for (i=0; i<[arr1 count]; i++) {
 for (j=i+1; j<[arr1 count]; j++) {
 tmpStr1=[arr1 objectAtIndex: i]; //star
 tmpStr2=[arr1 objectAtIndex:j]; //rats
 if ( tmpStr1.length == tmpStr2.length) { //4==4
 [newArr addObject:tmpStr1]; //newArray=[star]
 for (int k=0; k<tmpStr2.length; k++) {
 //Get the letter by letter in tmpStr2
 NSString cmpStr=[NSString stringWithFormat:@"%C",[tmpStr2 characterAtIndex:k]]];
 if ([tmpStr1 rangeOfString:cmpStr.location == NSNotFound) {
 Var=NO; //Characters in tmpStr2 not found in tmpStr1
 } else {
 Var=YES; //Characters in tmpStr2 found in tmpStr1
 }
 }
 //if all the letters in string tmpStr2 are present in string tmpStr1
 if (Var) { 
 //add the second string i.e. tmpStr2 to the array newArr
 [newArr addObject:tmpStr2]; 
 }
 }
 else
 {
 i=j; 
 //remove the duplicate strings in the array newArr
 //print the anagram set to log
 NSLog(@"NewArr::>%@",[[NSSet setWithArray:newArr] allObjects]); 
 //remove the objects in the array for the next set of anagrams
 [newArr removeAllObjects]; 
 //Controll goes to this line::> for (j=i+1; j<[arr1 count]; j++)
 continue; 
 }
 }
 }
 NSLog(@"Arr2::%@",[[NSSet setWithArray:newArr] allObjects]);
 NSLog(@"Arr1::%@",arr1); //To print the original array
 }



Find on Git: Here!
iOS:Database in applications usingFMDB Wrapper Class —

iOS:Database in applications usingFMDB Wrapper Class

  We can include the database in our iPad/iPhone applications with the help of   SQLite and FMDB wrapper class. Here is how we can achieve it with following simple steps.

1. First with the help of Mozilla Firefox SQLite plug-in create a MyDatabase.sqlite file and save it in your project folder.

2.Get the FMDB Wrapper classes from the git hub project  https://github.com/ccgus/fmdb unzip it and navigate to the fmdb folder (fmdb-master.zip\fmdb-master\src\fmdb) and copy this to your Xcode project.

 3. Write this piece of code in your appdelegate.m  in   file to make a connection to your MyDatabase.sqlite file  and save the path to your database in NSUserDefaults so that we can use it when we are doing any DB operations.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

//-------------------DataBase connection----------------------

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];



    // To Get the path of the database file during runtime of application

    NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"MYDatabase.sqlite"];

    NSLog(@"Database path: %@",databasePath);



    if ([fileManager fileExistsAtPath:databasePath] == NO) {

        NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"MYDatabase" ofType:@"sqlite"];

        [fileManager copyItemAtPath:resourcePath toPath:databasePath error:&error];

    }

    //save the database path in userdefaults  so that you can use it for connecting to database and making database operations

    [[NSUserDefaults standardUserDefaults] setValue:databasePath forKey:dbPath];

    [[NSUserDefaults standardUserDefaults] synchronize];

}

4. In ViewController.m file of your project import the two header files

#import "FMDatabase.h"
#import "FMResultSet.h"

then write the following code to connect to the database and make the insertion and selection operations in your app Database.

- (void)viewDidLoad
{

[self insertDataInDB];

//array  dbResultArray Has the resultant rows retrieved from db by SELECT Query

NSArray *dbResultArray=[NSArray arrayWithArray:[self getDataFromDB]] ;

//To store the data retrieved in a variables for use 

//Use your convenient way to store the  retrieved  data  and use it in your app

for(int i=0 ; i<dbResultArray.count;i++){
  NSString *str1=[[dbResultArray objectAtIndex:i] valueForKey:@"column1Value"];
  NSString *str2=[[dbResultArray objectAtIndex:i] valueForKey:@"column2Value"];  
.
.  
.
  NSString *strN=[[dbResultArray objectAtIndex:i] valueForKey:@"columnNValue"];
}//String 
}

This below method inserts the data in to database :

-(void)insertDataInDB
{
//Connec to database
NSString *dbPath=[[NSUserDefaults standardUserDefaults]valueForKey:dbPath];
FMDatabase *localDB = [FMDatabase databaseWithPath:dbPath];
[localDB open];
NSString *queryStr;

queryStr=[NSString stringWithFormat:@"INSERT INTO table_name (Collumn1,Collumn2,Collumn3,Collumn4,....,CollumnN) VALUES (Value1,'Value2','Value3','Value4',.....,'ValueN')"];

  if (![localDB executeUpdate:queryStr]) {

          //NSLog(@"failed Inserting data to DB: %@", [localDB lastErrorMessage]);

      }
 [localDB close];

}

This below method  returns the array of Dictionary containing the Retrieved data from database:

-(NSMutableArray *)getDataFromDB
{
//Connec to database
NSString *dbPath=[[NSUserDefaults standardUserDefaults]valueForKey:dbPath];
FMDatabase *localDB = [FMDatabase databaseWithPath:dbPath];
[localDB open];
NSMutableArray *tempArrayV=[[NSMutableArray alloc]init];     
NSString *queryStr=[NSString stringWithFormat:@"SELECT * from table_name"];
FMResultSet *resultQuery = [localDB executeQuery:queryStr];
//After the query is executed 
while ([resultQuery next]) {
NSDictionary * DataDict =[NSDictionary dictionaryWithObjectsAndKeys:
[resultQuery stringForColumn:@"Column1"],@"column1Value",
[resultQuery stringForColumn:@"Column2"],@"column2Value",
[resultQuery stringForColumn:@"Column3"],@"column3Value",
.
.
.
[resultQuery stringForColumn:@"ColumnN"],@"columnNValue",nil];
[tempArrayV addObject:DataDict];
}
return tempArrayV;
[localDB close];
}

Hope this will help you to implement the Application with the database support.

iOS – Architecture — January 14, 2015

iOS – Architecture

                   
                iOS is an operating system for the iPhone’s (an Apple Inc Product). It is derived from core OS X technologies ( an OS for MAC pc) .The iOS includes the OS X Kernel , BSD Sockets for Networking  and objective-C and C/C++ compilers for native performance. iOS 7.0 is the latest release of iOS on June 10 2013.


The iOS has the layered architecture, different layers are in the below figure.

Cocoa Touch is a UI framework for building software programs to run on the iOS operating system (for the iPhone, iPod Touch, and iPad) from Apple Inc.
Cocoa Touch mainly contains the classes implemented  in Objective-C, an object-oriented language that is compiled to run at incredible speed, yet employs a truly dynamic runtime making it uniquely flexible. Because Objective-C is a superset of C, it is easy to mix C and even C++ into your Cocoa Touch applications.
The framework’s of this layer provides provide the basic  app infrastructure and support for the key technologies ( .i.e Multitasking ,touch-based input, push notification and many  high level system services.)
UIKit Framework: This frame work provides the crucial infrastructure for implementing graphical ,event driven, apps in iOS.
The Media layer contains the graphics, audio, and video technologies you use to implement multimedia experiences in your apps. The technologies in this layer make it easy for you to build apps that look and sound great.
The technologies of this layer are listed as below:


Core Services Layer:

This Layer contains basic system services for apps. Core Foundation and Foundation Frameworks are the key services provided by this layer, which define the basic types that all apps use it also has the technologies which supports the features like location, iCloud,social media and networking.
Some of the High-Level Features and Frameworks provided by this layer are:

This layer contains the low-level features on basis of which the other high-level features are built.Even though we do not use any of these features directly in our  apps ,they used by the frameworks which are used by our application.We can make use of these features when we need to implement the security features  or communicating with an external hardware accessory.
Frameworks provided by this layer are: