Monday, 22 June 2015

MapView for iOS - Mark Places using Latitude & Longitude Values

Add the Frameworks: MapKit, CoreLocation

Create a New File for MapViewController & Add the Below Code’s


MapViewController.h
#import <MapKit/MapKit.h>

@interface MapViewController : UIViewController <MKMapViewDelegate>

@property (weaknonatomicIBOutlet UISegmentedControl *segment_view;
@property (weaknonatomicIBOutlet MKMapView *map_view;

- (IBAction)change_type:(id)sender;
- (IBAction)Route_Map:(id)sender;

@property (nonatomic,strongNSString *lati;
@property (nonatomic,strongNSString *longi;

@end


MapViewController.m
#import "MapViewController.h"

@interface MapViewController ()
@end

@implementation MapViewController

@synthesize map_view, segment_view;

- (void)viewDidLoad
{
    [super viewDidLoad];
    map_view.delegate = self;
map_view.mapType = MKMapTypeStandard;

    [self showLocate];
}


// Zoom Out & Shows full map
-(void)zoomOut
{
    // step.1 create co-ordianate-span as follows
    MKCoordinateSpan span = {.latitudeDelta = 180, .longitudeDelta = 360};
    
    // step.2 crate region as follows
    MKCoordinateRegion region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(0.0000f0.0000f), span);
    
    // step.3 zoom using region to map as follows
    [map_view setRegion:region animated:YES];
}


- (void)showLocate
{
    //Set the Location
    self.lati = @"12.0000";
    self.longi = @"76.0000";
    
    for (int i = 0; i < 3; i++)
    {
        MKLocalSearchRequest *request = [[MKLocalSearchRequest allocinit];
        NSString *str = [NSString stringWithFormat:@"%f,%f",12.000+i,76.000+i];
        NSLog(@"%@",str);
        request.naturalLanguageQuery = str;
        request.region = map_view.region;
        
        NSMutableArray *_matchingItems = [[NSMutableArray allocinit];
        
        MKLocalSearch *search =
        [[MKLocalSearch alloc]initWithRequest:request];
        
        [search startWithCompletionHandler:^(MKLocalSearchResponse
                                         *response, NSError *error) {
        if (response.mapItems.count == 0)
            NSLog(@"No Matches");
        else
            for (MKMapItem *item in response.mapItems)
            {
                [_matchingItems addObject:item];
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
                annotation.coordinate = item.placemark.coordinate;
                //set the Title for Annotation
                annotation.title = store_model.str_area_name;
                annotation.subtitle = store_model.str_address;
                [map_view addAnnotation:annotation];
                CLLocationCoordinate2D ll = CLLocationCoordinate2DMake([self.lati doubleValue], [self.longi doubleValue]);
                MKCoordinateSpan span = MKCoordinateSpanMake(0.010.01);
                MKCoordinateRegion region = MKCoordinateRegionMake(ll, span);
                [map_view setRegion:[map_view regionThatFits:region] animated:YES];
                [map_view setCenterCoordinate:ll animated:YES];
                [map_view selectAnnotation:annotation animated:YES];
            }
    }];
    
    [self performSelector:@selector(zoomInToMyLocation)withObject:nil afterDelay:2];
    }
}


-(void)zoomInToMyLocation
{
    MKCoordinateRegion region = { {0.00.0 }, { 0.00.0 } };
    region.center.latitude = [self.lati floatValue];
    region.center.longitude = [self.longi floatValue];
    region.span.longitudeDelta = 0.01f;
    region.span.latitudeDelta = 0.01f;
    [map_view setRegion:region animated:YES];
    
    [map_view setDelegate:self];
}


//Custom Annotations for iOS - If u want the Custom Pin add this code
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
    {
        return nil;
    }
    else
    {
        static NSString * const identifier = @"MyCustomAnnotation";
        MKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        
        if (annotationView)
        {
            annotationView.annotation = annotation;
        }
        else
        {
            annotationView = [[MKAnnotationView allocinitWithAnnotation:annotation reuseIdentifier:identifier];
        }
        // set your annotationView properties
        annotationView.image = [UIImage imageNamed:@"pin_red.png"];
        annotationView.centerOffset = CGPointMake(0, -10);
        annotationView.canShowCallout = YES;
        
        //if you add QuartzCore to your project, you can set shadows for your image
        [annotationView.layer setShadowColor:[UIColor blackColor].CGColor];
        [annotationView.layer setShadowOpacity:1.0f];
        [annotationView.layer setShadowRadius:5.0f];
        [annotationView.layer setShadowOffset:CGSizeMake(00)];
        //[annotationView setBackgroundColor:[UIColor whiteColor]];
        
        return annotationView;
    }
    return nil;
}


- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    //[mapView deselectAnnotation:view.annotation animated:YES];

//SplashScreenViewController *infoView = [[SplashScreenViewController alloc]initWithNibName:@"SplashScreenViewController" bundle:nil];
//[self.navigationController pushViewController:infoView animated:YES];
    
    if ([view.annotation.title isEqualToString@"40.724200,74.172600"])
    {
        NSLog(@"loaded");

    }
    else if ([view.annotation.title isEqualToString@"12.000000,76.000000"])
    {
        NSLog(@"loaded");
    }
}


- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    NSLog(@"%@",userLocation);
}


- (IBAction)change_type:(id)sender
{
    if(segment_view.selectedSegmentIndex == 0)
    {
        map_view.mapType = MKMapTypeStandard;
    }
    else if(segment_view.selectedSegmentIndex == 1)
    {
        map_view.mapType = MKMapTypeSatellite;
    }
    else if(segment_view.selectedSegmentIndex == 2)
    {
        map_view.mapType = MKMapTypeHybrid;
    }

}

Find the Date, Time & Day Value in iOS

.m File:
-(void)date_time
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MMM dd, yyyy HH:mm"];
    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setDateFormat:@"HH:mm:ss"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
    [dateFormatter setDateFormat:@"EEEE"];
    
    NSDate *now = [[NSDate alloc] init];
    NSString *dateString = [format stringFromDate:now];
    NSString *theDate = [dateFormat stringFromDate:now];
    NSString *theTime = [timeFormat stringFromDate:now];
    
    NSString *day_value = [dateFormatter stringFromDate:now];
    NSLog(@"\n"
          "theDate: |%@| \n"
          "theTime: |%@| \n"
          "Now: |%@| \n"
          "Day: |%@| \n"
          
          , theDate, theTime,dateString,day_value);

}

In iOS, Check & UnCheck the items in Tableview

.m File:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    [cell.textLabel setText:[NSString stringWithFormat:@"Row %d", indexPath.row]];
    
    NSIndexPath* selection = [tableView indexPathForSelectedRow];
    if (selection && selection.row == indexPath.row) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    // Configure the cell.
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}


In TableView, Add Footer and Remove Insets for iOS

Remove the Selection Index from Tableview
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%d", indexPath.row);
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
}


Footer for Tableview
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,tableView.frame.size.width, 1)];
    [footerView setBackgroundColor:[UIColor lightGrayColor]];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}


Remove Insets Spaces in Tableview for iOS 8
-(void)viewDidLayoutSubviews
{
    // iOS 8 separator inset 0
    if ([Table_View respondsToSelector:@selector(setLayoutMargins:)])
    {
        [Table_View setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell1 forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // iOS 8 separator inset 0
    
    if ([cell1 respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell1 setLayoutMargins:UIEdgeInsetsZero];
    }

}

Check the URL Status Code & Download a PDF File in iOS

200 - Success
404 - Page Not Found
500 - Internel Server Error

.m File:
-(void)testing_function
{
    // Get the PDF Data from the url in a NSData Object
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/info.pdf"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    [request setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse* response = nil;
    NSError* error = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"statusCode = %d", [response statusCode]);
    
    if ([response statusCode] == 200)
    {
        NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.example.com/info.pdf"]];
        
        // Store the Data locally as PDF File
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Result.pdf"];
        [pdfData writeToFile:filePath atomically:YES];
        
        // Now create Request for the file that was saved in your documents folder
        NSURL *url = [NSURL fileURLWithPath:filePath];
        docController = [UIDocumentInteractionController alloc];
        docController = [UIDocumentInteractionController interactionControllerWithURL:url];
        BOOL isValid = [docController presentOpenInMenuFromRect:pdfIcon.frame inView:self.view animated:YES];
        docController.delegate = self;
        
        if(isValid)
        {
            docController.delegate = self;
        }
        else
        {
            UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"Sorry" message:@"You need iBooks to view this file" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Install", nil];
            [alert show];
        }
    }
}

Motion Detection for iOS

.h File :
#import <CoreMotion/CMMotionActivityManager.h>
#import <CoreMotion/CMMotionActivity.h>
#import <CoreMotion/CMStepCounter.h>

@interface ViewController : UIViewController
{
    CMMotionActivityManager *motionActivityManager;
}

@end


.m File :
View DidLoad or ViewWillAppear
[self check_MotionDetector];

#pragma mark - Motion Detection
-(void)check_MotionDetector
{
    motionActivityManager = [[CMMotionActivityManager alloc] init];
    [motionActivityManager startActivityUpdatesToQueue:[[NSOperationQueue alloc]init]withHandler:^(CMMotionActivity *activity) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([activity running])
            {
                [self doExit:@"Automotive"];
            }
            else if ([activity cycling])
            {
                [self doExit:@"Automotive"];
            }
            else if ([activity automotive])
            {
                [self doExit:@"Automotive"];
            }
        });
    }];
}

-(void)doExit:(NSString *)MotionType
{
    if ([MotionType isEqualToString:@"Automotive"])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                        message:@"Do you drive the car?"
                                                       delegate:self
                                              cancelButtonTitle:@"No"
                                              otherButtonTitles:@"Yes", nil];
        [alert show];
        [alert setTag:100];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)
    {
        if (buttonIndex == 0)
        {
            [motionActivityManager stopActivityUpdates];
        }
        else if (buttonIndex == 1)
        {
            //home button press programmatically
            UIApplication *app = [UIApplication sharedApplication];
            [app performSelector:@selector(suspend)];
            
            //wait 2 seconds while app is going background
            [NSThread sleepForTimeInterval:1.0];
            
            //exit app when app is in background
            exit(0);
        }
    }
}

Saturday, 15 November 2014

In Horizontal Scrollview to Find a page using Page Controller

In ScrollView Settings, Tick the PagingEnabled Button.


ViewController.m File

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = scroll.contentOffset.x / scroll.frame.size.width;
    page_controll.currentPage = page;
}