Wednesday, 21 October 2015

Apple Map ( device Default ) With Path

Apple MAP WITH PATH



 1 ) set Delegate in .h file :- CLLocationManagerDelegate

#import <CoreLocation/CoreLocation.h>

#import <MapKit/MapKit.h>


 2 ) Then Write this in Your method :-


 CLLocationManager *locationManager = [[CLLocationManager alloc] init] ;
    
    locationManager.delegate = self ;
    
    locationManager.distanceFilter = kCLDistanceFilterNone ;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest ;
    
    float mycurrentLatitude = locationManager.location.coordinate.latitude ;
    float mycurrentLongitude = locationManager.location.coordinate.longitude ;
    
    NSLog(@"%f",locationManager.location.coordinate.latitude);
    
    [locationManager startUpdatingLocation] ;
    [locationManager  requestWhenInUseAuthorization] ;
    
    //---------- destination Location
    
    CLLocationCoordinate2D cordinate = CLLocationCoordinate2DMake([_selectedLatitudeValue floatValue], [_selectedLongitudeValue floatValue]) ;
    MKPlacemark *eventPlaceMark = [[MKPlacemark alloc] initWithCoordinate:cordinate addressDictionary:nil] ;
    MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:eventPlaceMark] ;
    [mapItem setName:[NSString stringWithFormat:@"%@",_selectedEventAddress]];
    
    //---------- Current Location
    
    CLLocationCoordinate2D currentCordinate = CLLocationCoordinate2DMake(mycurrentLatitude , mycurrentLongitude ) ;
    MKPlacemark *currentPlaceMark = [[MKPlacemark alloc] initWithCoordinate:currentCordinate addressDictionary:nil] ;
    MKMapItem *currentMapItem = [[MKMapItem alloc] initWithPlacemark:currentPlaceMark] ;
    [currentMapItem setName:@"current location"];
    [MKMapItem openMapsWithItems:@[mapItem , currentMapItem] launchOptions:@{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving}] ;


Saturday, 3 October 2015

Pick Image From Gallery or Camera & Post on Server

Pick Image From Gallery or Camera & Post



In Appdelegate :

1 ) Import In viewcontroller.h :-

Framework :- MediaPlayer

#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAsset.h>


Set Delegate :- UIImagePickerControllerDelegate >

@property (strong,nonatomic) MPMoviePlayerController *player;


2 ) Use In viewcontroller.m :-

- (IBAction)addmedia:(id)sender
{
   
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Add Poster?" delegate:self cancelButtonTitle:@"Photo Library" otherButtonTitles:@"Camera", nil];
        [alert setTag:1];
        [alert show];
        
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 1)
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        imagePicker.delegate = self;
        NSArray *mediaTypesAllowed = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary | UIImagePickerControllerSourceTypeCamera];
        [imagePicker setMediaTypes:mediaTypesAllowed];
        
        if(buttonIndex == [alertView cancelButtonIndex])
        {
            imagePicker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.allowsEditing = YES;
        }
        else
        {
            if(buttonIndex == 1)
            {
                imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
                imagePicker.allowsEditing = YES;
            }
        }
        [self presentViewController:imagePicker
                           animated:YES completion:nil];
    }
}


#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    _mediaView.frame = CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height) ;
    
    [self.view addSubview:_mediaView];
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSURL *url = info[UIImagePickerControllerMediaURL];
    
    mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
        UIImageWriteToSavedPhotosAlbum(image, self,
                                       @selector(image:finishedSavingWithError:contextInfo:),
                                       nil);
        
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSString stringWithFormat:@"%@",url]))
        {
            UISaveVideoAtPathToSavedPhotosAlbum([NSString stringWithFormat:@"%@",url],
                                                self,
                                                @selector(video:finishedSavingWithError:contextInfo:),
                                                nil);
        }
    }
    
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypePhotoLibrary])
    {
        
        //check the media type string so we can determine if its a video
       if ([mediaType isEqualToString:@"public.movie"]){
        NSLog(@"info:%@",info);
        videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        // NSData *webData = [NSData dataWithContentsOfURL:videoURL];
        _player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
           [_player.view setFrame:self.mediaImage.frame];
          AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
          NSTimeInterval durationInSeconds = 0.0;
           if (asset)
               durationInSeconds = CMTimeGetSeconds(asset.duration);
            NSLog(@"duration:%f",durationInSeconds);
           
          
          if(durationInSeconds > 6.0){
           [[[UIAlertView alloc] initWithTitle:nil
                                       message:@"You can only upload 6sec Video."
                                      delegate:nil
                             cancelButtonTitle:nil
                             otherButtonTitles:@"Ok", nil] show];
           }
           else
           {
               [_player.view setFrame:_mediaView.frame];
               [self.mediaView addSubview:_player.view];
               [_player play];
               
           }

    }
    if([mediaType isEqualToString:@"public.image"])
    {
        [_player.view removeFromSuperview];
       
        self.mediaImage.image=[info objectForKey:UIImagePickerControllerOriginalImage];

    }
    }
    
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)image:(UIImage *)image
finishedSavingWithError:(NSError *)
error contextInfo:(void *)contextInfo
{
    if (error) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle: @"Save failed"
                              message: @"Failed to save image/video"
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
}


-(void)video:(UIImage *)image
finishedSavingWithError:(NSError *)
error contextInfo:(void *)contextInfo
{
    if (error) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle: @"Save failed"
                              message: @"Failed to save image/video"
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//------------------------------------------------------------

//-------Post Image or Video Using ASIFormDataRequest


if ([mediaType isEqualToString:@"public.movie"])
       {
           
            NSData *uploadData = [NSData dataWithContentsOfURL:videoURL];
            [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];
            [request setData:uploadData withFileName:@"hangover.mp4" andContentType:@"multipart/form-data" forKey:@"video"];

           
       }
       else if([mediaType isEqualToString:@"public.image"])
       {
        
        
        NSData *imgData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((_mediaImage.image), 0.5)];
    
        [request setPostFormat:ASIMultipartFormDataPostFormat];
        
        [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];
        
        [request setData:imgData withFileName:@"abc.jpg" andContentType:@"multipart/form-data" forKey:@"image"];

       }

Get IPAddress of Device or Simulator

Get IPAddress of Device or Simulator



1 ) Import In viewcontroller.h :-

#import <ifaddrs.h>
#import <arpa/inet.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>


1 ) Write In viewcontroller.m :-

- (NSString *)getIPAddress
{

     //-------- For Devices only
     
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    NSLog(@"%@",address);
    
    _strIpAddress = address ;
    
    return address;
     
    //-------- for Simulator
    
    int mgmtInfoBase[6];
    char *msgBuffer = NULL;
    NSString *errorFlag = NULL;
    size_t length;
    
    mgmtInfoBase[0] = CTL_NET; // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE; // Routing table info
    mgmtInfoBase[2] = 0;
    mgmtInfoBase[3] = AF_LINK; // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
        errorFlag = @"if_nametoindex failure";
    // Get the size of the data available (store in len)
    else if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
        errorFlag = @"sysctl mgmtInfoBase failure";
    // Alloc memory based on above call
    else if ((msgBuffer = malloc(length)) == NULL)
        errorFlag = @"buffer allocation failure";
    // Get system information, store in buffer
    else if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0) {
        free(msgBuffer);
        errorFlag = @"sysctl msgBuffer failure";
    }
    else
    {
        // Map msgbuffer to interface message structure
        struct if_msghdr *interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
        // Map to link-level socket structure
        struct sockaddr_dl *socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
        // Copy link layer address data in socket structure to an array
        unsigned char macAddress[6];
        memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
        // Read from char array into a string object, into traditional Mac address format
        NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                      macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]];
        NSLog(@"Mac Address: %@", macAddressString);
        free(msgBuffer);
         _strIpAddress = macAddressString ;
        return macAddressString;
    }

    NSLog(@"Error: %@", errorFlag);
    return nil;

    
}

Database (Programatically Create DB)

Database ( Programatically Create DB )


SQLManager.h : -

#import <Foundation/Foundation.h>
#import "sqlite3.h"

@interface SQLManager : NSObject
{
    char *errorDB ;
}

@property (assign , nonatomic) sqlite3 *DB ;

/* Open DB And Create table if not exist  */

-(void)createAndOpenDatabase ;

/* Get All User Info Details */

-(NSMutableDictionary *)getAllUserInfo ;

/* Insert User Data to "user_data" Table */

-(BOOL)insertKeyToDatabase:(NSString *)key value:(NSString *)value ;
-(BOOL)updateKeyToDatabase:(NSString *)key value:(NSString *)value ;


@end

SQLManager.m : -

#import "SQLManager.h"


@implementation SQLManager

@synthesize DB ;

#pragma mark - Database Methods

-(void)createAndOpenDatabase
{
    //NSLog(@"called") ;
    
    [self openDB];
    [self createTable] ;
}

-(NSString *)documentsPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [paths objectAtIndex:0];
    NSLog(@"%@",paths);
    return [documentDir stringByAppendingPathComponent:@"Database.sqlite"];
}

-(void)openDB
{
    if (sqlite3_open([[self documentsPath]UTF8String],&DB) == SQLITE_OK)
    {
        // NSLog(@"database opened");
    }
    else
    {
        sqlite3_close(DB);
        NSAssert(0, @"database failed to open");
    }
}

-(void) createTable
{
    // Table - [ User Data Table ]
    
    NSString *tableName = @"user_data";
    NSString *field1 = @"id";
    NSString *field2 = @"key";
    NSString *field3 = @"value";
    
    NSString *sql_stat = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' " "INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT,'%@' TEXT);",tableName, field1, field2,field3];
    
    if (sqlite3_exec(DB, [sql_stat UTF8String], NULL, NULL, &errorDB) == SQLITE_OK &&
        sqlite3_exec(DB, [sql_stat UTF8String], NULL, NULL, &errorDB) == SQLITE_OK)
    {
        // NSLog(@"Table1 Created");
    }
    else
    {
        sqlite3_close(DB);
        NSAssert(0, @"Tabled failed to create.");
    }
}

#pragma mark - Get Data from DB

-(NSMutableDictionary *)getAllUserInfo
{
    NSMutableDictionary *userInfoDict = [[NSMutableDictionary alloc] init] ;
    
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    NSMutableArray *valueArray = [[NSMutableArray alloc] init];
    
    NSString *display = [NSString stringWithFormat:@"SELECT * FROM user_data"];
    
    sqlite3_stmt *statement ;
    
    if (sqlite3_prepare_v2(DB, [display UTF8String], -1, &statement, nil) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            char *field = (char *) sqlite3_column_text(statement, 1);
            NSString *fieldStr = [[NSString alloc] initWithUTF8String:field];
            
            char *field2 = (char *) sqlite3_column_text(statement, 2);
            NSString *fieldStr2 = [[NSString alloc] initWithUTF8String:field2];
            
            [keyArray addObject:fieldStr] ;
            [valueArray addObject:fieldStr2] ;
        }
    }
    
    for (int i = 0 ; i < keyArray.count ; i++)
    {
        [userInfoDict setValue:[valueArray objectAtIndex:i] forKey:[keyArray objectAtIndex:i]] ;
    }
    
    return userInfoDict ;
}

#pragma mark - Insert User Data to table

-(BOOL)insertKeyToDatabase:(NSString *)key value:(NSString *)value
{
    NSString *insertTag = [NSString stringWithFormat:@"INSERT INTO user_data ('key','value') VALUES ('%@','%@')", key , value];
    
    if (sqlite3_exec(DB, [insertTag UTF8String], NULL, NULL, &errorDB) == SQLITE_OK)
    {
        return YES ;
    }
    else
    {
        return NO ;
    }
}
-(BOOL)updateKeyToDatabase:(NSString *)key value:(NSString *)value
{
           NSString *updateTag = [NSString stringWithFormat:@"INSERT OR REPLACE INTO user_data  ('key','value') VALUES ('%@','%@')", key , value];
    
    if (sqlite3_exec(DB, [updateTag UTF8String], NULL, NULL, &errorDB) == SQLITE_OK)
    {
        return YES ;
    }
    else
    {
        return NO ;
    }
}

@end


//------------------------------------------------

Check Status For Login :


1 ) Import In Appdelegate.h :-

#import "SQLManager.h"

//------------assign property--------------//

//-------- SqlManager Obj -------//

@property (strong , nonatomicSQLManager *sqlObj ;

2 ) Use In viewcontroller.m :-

// ------- didFinishLaunchingWithOptions Method

      [self sqlCheck] ;

     
    if ([self userAlreadyLoggedIn])
    {

        NSLog(@"Logged in") ;
   
    }
    else
    {

        NSLog(@"Not Logged in") ;
      

    }

// ------- Create Method

#pragma mark - Create Local Sqlite

-(void)sqlCheck
{
    _sqlObject = [[SQLManager alloc] init] ;
    [_sqlObject createAndOpenDatabase] ;
}

#pragma mark - Check User Log in Status

-(BOOL)userAlreadyLoggedIn
{
    NSString *userLoggedIn = [[_sqlObject getAllUserInfo] valueForKey:@"user_logged_in"] ;
    
    if ([userLoggedIn isEqualToString:@"yes"])
    {
        return YES ;
    }
    else
    {
        return NO ;
    }

}

//------------------------------------------------
Use Of Database In ViewController :

1 ) Import In viewcontroller.h :-

#import "SQLManager.h"

//------------assign property--------------//

//-------- SqlManager Obj -------//

@property (strong , nonatomic) SQLManager *sqlObj ;

2 ) Use In viewcontroller.m :-

 // ---------- Initialize SqlObject
    
    _sqlObj = [[SQLManager alloc] init] ;


 //------- Open Sql DB
    
    [_sqlObj createAndOpenDatabase] ;


//---------- Insert data by key


   ex. -  [_sqlObj insertKeyToDatabase:@"user_logged_in" value:@"yes"];
              [_sqlObj insertKeyToDatabase:@"name" value:txtname.text];
              [_sqlObj insertKeyToDatabase:@"add" value:txtadd.text];
   

   
//---------- Get data by key

ex. -  [_sqlObj getAllUserInfo] valueForKey:@""];


Update Data Model Object

UPDATE DATA MODEL OBJECT


            dataModelObj = _obj.data[openedSectionIndex];
            
            NSDictionary* dict = [dataModelObj toDictionary];
            NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
            [newDict addEntriesFromDictionary:dict];
            [newDict removeObjectForKey:@"save_cnt"];
            [newDict removeObjectForKey:@"saved_status"];
            
            [newDict setObject:[responseDict valueForKey:@"savecount"] forKey:@"save_cnt"];
            [newDict setObject:[responseDict valueForKey:@"saved_status"] forKey:@"saved_status"];
            NSArray* jsonObjects = [MainModel_EventListing arrayOfDictionariesFromModels: _obj.data];
            
            tmpDataForUnSave=[[NSMutableArray alloc]init];
            
            for(int j=0;j<jsonObjects.count;j++)
            {
                
                [tmpDataForUnSave addObject:jsonObjects[j]];
                if([dataModelObj.name isEqualToString:[jsonObjects[j] valueForKey:@"name"]])
                {
                    [tmpDataForUnSave replaceObjectAtIndex:j withObject:newDict];
                }
                
            }
             _obj.data=nil;
            NSMutableDictionary* result = [[NSMutableDictionary alloc]init];
            [result setObject:tmpDataForUnSave forKey:@"data"];
           
            _obj = [[MainModel_EventListing alloc] initWithDictionary:result error:nil] ;
           
            //[self.sections removeAllObjects];
            
            NSLog(@"new-dict:%@",_obj.data);
            for (int i = 0 ; i <_obj.data.count ; i++)
            {
                //--------------- Data Model Object
      
                dataModelObj = _obj.data[i] ;

              }