Sunday, August 4, 2013

Find latitude and longitude in iOS

Before starting coding, first add coreLocation framework in Application.

Now move to Coding part.

.h file

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

.m file
- (void)viewDidLoad
{

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy =kCLLocationAccuracyNearestTenMeters;


//kCLLocationAccuracyBestForNavigation;// use high level of accuracy including additinal sensor data,this level of accuracy is intended solely to use when device is connected with exteranl power supply.
 //  kCLLocationAccuracyBest -- highest level of accuracy for device running on batter power
    //  kCLLocationAccuracyHundredMeters - accurate within 100 meter
    //  kCLLocationAccuracyKilometer - accurate within km
    //  kCLLocationAccuracyNearestTenMeters - accurate within 10 meter
    //  kCLLocationAccuracyThreeKilometers -  accurate within 3 km
    
    //-------------------


locationManager.distanceFilter = 30.48f//mts for 100 feet
[locationManager startUpdatingLocation];
}

// for ios5 it is deprecated in ios6
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;
    if (currentLocation != nil) {
        AppDelegate *appD = [[UIApplication sharedApplication] delegate];
        Location *objLocation = [NSEntityDescription insertNewObjectForEntityForName:tblLocation inManagedObjectContext:appD.managedObjectContext];
        //NSLog(@"%@",[NSString stringWithFormat:@"%f", currentLocation.coordinate.latitude]);
        objLocation.latitude = [NSString stringWithFormat:@"%f", currentLocation.coordinate.latitude];
        objLocation.longitude =  [NSString stringWithFormat:@"%f", currentLocation.coordinate.longitude];
        objLocation.timeStamp = [dateFormater stringFromDate: [NSDate date]];
        NSLog(@"latittude:%@,longitude%@",objLocation.latitude,objLocation.longitude);
    }
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
    NSLog(@"Enter Region");
}
-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
{
    NSLog(@"Start Monitoring Region");
}
-(void)locationManagerDidResumeLocationUpdates:(CLLocationManager *)manager
{
    NSLog(@"Resume Location update");
    
}

// Change set ios6 location manager above is depreciated-------
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *curr=[locations lastObject];
    // NSDate *eventDate=curr.timestamp;
    // NSTimeInterval howEvent=[eventDate timeIntervalSinceNow];
    //    if(abs(howEvent) <15.0)
    //    {
    if(curr!=nil)
    {
        AppDelegate *appD = [[UIApplication sharedApplication] delegate];
        Location *objLocation = [NSEntityDescription insertNewObjectForEntityForName:tblLocation inManagedObjectContext:appD.managedObjectContext];
        //NSLog(@"%@",[NSString stringWithFormat:@"%f", currentLocation.coordinate.latitude]);
        objLocation.latitude = [NSString stringWithFormat:@"%f", curr.coordinate.latitude];
        objLocation.longitude =  [NSString stringWithFormat:@"%f", curr.coordinate.longitude];
        objLocation.timeStamp = [dateFormater stringFromDate: [NSDate date]];
        lat=curr.coordinate.latitude;
        lon=curr.coordinate.longitude;
        
    }
    // }
    NSLog(@"%f,%f",curr.coordinate.longitude,curr.coordinate.latitude);
}




Wednesday, June 26, 2013

Store image in Document Directory and Retrieve it in iOS

In this Example i will show how to store image in document directory and Retrieve it.

Following Method we will use to store.

1.NSSearchPathForDirectoriesInDomains : Creates a list of directory search paths. Creates a list of path strings for the specified directories in the specified domains. The list is in the order in which you should search the directories. If expandTilde is YES, tildes are expanded as described in stringByExpandingTildeInPath. You should consider using the NSFileManager methods URLsForDirectory:inDomains: and URLForDirectory:inDomain:appropriateForURL:create:error:. which return URLs, which are the preferred format.

Let Start
here imgData is in NSData Format.

 >>Storing image in document Directory.


NSData *imgData=UIImagePNGRepresentation([UIImage imageNamed:@"Test.png"]);


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *localFilePath= [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"frame_%d.jpeg",1]];
            NSLog(@"local file path at save --------------- %@",localFilePath);
[imgData writeToFile:localFilePath atomically:YES];

 >> Retrieve Image from document Directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath= [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"frame_%d.jpeg",1]];
    


UIImage *givenImage = [UIImage imageWithContentsOfFile:localFilePath];


NSData *myimg =  UIImageJPEGRepresentation(givenImage,0.5);
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
img.image=[UIImage imageWithData:myimg];
[self.view addSubview:img];


            


Sunday, June 16, 2013

Get Size and Resolution of iOS Device

In the Example I will show you how you get Actual Pixel Resolution and size of iOS Device by coding.

Just you have to find the Screen size bound and scale.


CGRect rect=[[UIScreen mainScreen] bounds];
    CGFloat scale=[[UIScreen mainScreen] scale];
    
    NSLog(@"Actual Pixel Resolution: width :% f,height :%f",rect.size.width * scale,rect.size.height * scale);
     NSLog(@" Actual Size width :% f,height :%f",rect.size.width ,rect.size.height );

O/P
For retina 4-inch display
Actual Pixel Resolution: width : 640.000000,height :1136.000000
Actual Size width : 320.000000,height :568.000000


Monday, June 10, 2013

Move or Delete UiTableViewCell in iOS

In this example i will show how to move or delete cell in TableView.
First take UiTableView, allocate it datasource and delegate to File's Owner.

.h

#import <UIKit/UIKit.h>

@interface FavouriteListVC : UITableViewController
-(IBAction)btnEdit:(id)sender;
@end


.m
ViewDidLoad.


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIBarButtonItem *btn=[[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(btnEdit:)];
    btn.tag=10;
    self.navigationItem.rightBarButtonItem=btn;

}
-(IBAction)btnEdit:(id)sender
{
    int tag=[sender tag];
    if(tag==10)
    {
    [self.tableView setEditing:YES animated:YES];
    [sender setTitle:@"Done"];
        self.editing=YES;
        [sender setTag:11];
    }
    else
    {
        [self.tableView setEditing:NO animated:YES];
        [sender setTitle:@"Edit"];
        [sender setTag:10];
    }
}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSObject *obj=[self.favList objectAtIndex:sourceIndexPath.row];
if(destinationIndexPath.row>sourceIndexPath.row)
{
    for(int x=destinationIndexPath.row;x>sourceIndexPath.row;x--)
    {
        [self.favList replaceObjectAtIndex:x-1 withObject:[self.favList objectAtIndex:x]];
    }
}
    else
    {
        for(int x=destinationIndexPath.row;x<sourceIndexPath.row;x++)
        {
            [self.favList replaceObjectAtIndex:x+1 withObject:[self.favList objectAtIndex:x]];
        }
    }
    [self.favList replaceObjectAtIndex:destinationIndexPath.row withObject:obj];
    
}
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle==UITableViewCellEditingStyleDelete)
{
    [self.favList removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:

[NSArray arrayWithObject:indexPath]
         withRowAnimation:UITableViewRowAnimationFade];
   
}

}


Thursday, May 30, 2013

Face Detection Example in iOS

Here in this Example i will show how to detect face on image.

Here we need two framework CoreImage & QuartzCore.
Let Start.
.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (retain, nonatomic) IBOutlet UIButton *btnScanFace;
- (IBAction)btnScanFace:(id)sender;
@property (retain, nonatomic) IBOutlet UIImageView *imgView;
@end

.m
#import "ViewController.h"
#import <CoreImage/CoreImage.h>
#import <QuartzCore/QuartzCore.h>


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.imgView.image=[UIImage imageNamed:@"family.png"];
}

- (IBAction)btnScanFace:(id)sender {
 // draw a CI image with the previously loaded picture
    CIImage* image1=[CIImage imageWithCGImage:self.imgView.image.CGImage];
 // create a face detector - since speed is not an issue we'll use a high accuracy

    // detector


    CIDetector* detector1=[CIDetector detectorOfType:CIDetectorTypeFace context:nil options:[NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]];
// create an array containing all the detected faces from the detector  

    NSArray *feature1=[detector1 featuresInImage:image1];
    NSLog(@"%d",[feature1 count]);
// Here i use frameview because ciimage and uiimage are inversely if we leave as it is than detection will occur but show in different direction. 
    UIView *frameview=[[UIView alloc] initWithFrame:CGRectMake(self.imgView.bounds.origin.x, self.imgView.bounds.origin.y, self.imgView.image.size.width, self.imgView.image.size.height)];

 // we'll iterate through every detected face.  CIFaceFeature provides us
    // with the width for the entire face, and the coordinates of each eye
    // and the mouth if detected.  Also provided are BOOL's for the eye's and
    // mouth so we can check if they already exist.

    for (CIFaceFeature * faceFeature1 in feature1) {

// create a UIView using the bounds of the face
        //UIView* faceView1 = [[UIView alloc] initWithFrame:faceFeature.bounds];
UIView *faceView1=[[UIView alloc]initWithFrame:CGRectMake(faceFeature1.bounds.origin.x, faceFeature1.bounds.origin.y-15, faceFeature1.bounds.size.width, faceFeature1.bounds.size.height + 40)];

// Border is set
faceView1.layer.borderWidth=1;
faceView1.layer.borderColor=[[UIColor blackColor] CGColor];
[frameview addSubview:faceView1];
}

    [frameview setTransform:CGAffineTransformMakeScale(1, -1)];
    [self.view addSubview:frameview];
}