Thursday, 31 December 2015

Set Index


Inside Tableview

[cell2 insertSubview:viewname atIndex:0];

OR

View

[self insertSubview:viewname atIndex:0];

Tuesday, 22 December 2015

Check found (or) not found

   NSString *string = @"smviswa@gmail.com";
    if ([string rangeOfString:@"@"].location != NSNotFound) {
        NSLog(@"found");
    }else{
        NSLog(@"not found");

    }

Thursday, 17 December 2015

NSDictionary json convert to section and array

Get json example:

(
        {
        "au_id" = 2;
        "au_name" = viswanathan;
        items =         (
                        {
                "aef_food_category" = 2;
                "aef_id" = 3;
            },
                        {
                "aef_food_category" = 1;
                "aef_id" = 8;
            },
                        {
                "aef_food_category" = 4;
                "aef_id" = 10;
            }
        );
    },
        {
        "au_id" = 3;
        "au_name" = "Arvind Kumar";
        items =         (
                        {
                "aef_food_category" = 4;
                "aef_id" = 9;
            },
                        {
                "aef_food_category" = 2;
                "aef_id" = 1;
            }
        );
    },
        {
        "au_id" = 4;
        "au_name" = abi;
        items =         (
                        {
                "aef_food_category" = 1;
                "aef_id" = 6;
            }
        );
    }

)

Convert to section and array:


NSMutableDictionary *sections;

 for (NSDictionary *dataDict in jsonObjects)
    {
        NSString *title_str = [dataDict objectForKey:@"au_name"];
        [sections setValue:[[NSMutableArray alloc] init] forKey:title_str];
    }
   
    for(NSDictionary *dataDict in jsonObjects) {
        id items = [dataDict objectForKey:@"items"];
        NSString *str_user_id = [dataDict objectForKey:@"au_id"];
        for (NSDictionary *itemDict in items) {
            NSString *str_foodid = [itemDict objectForKey:@"aef_id"];
            NSString *str_foodcate = [itemDict objectForKey:@"aef_food_category"];
            
            NSDictionary *foodDict = [NSDictionary dictionaryWithObjectsAndKeys:
                        str_user_id, @"au_id",
                        str_foodid, @"aef_id",
                        str_foodcate, @"aef_food_category",
                        nil];            
            [[sections objectForKey:[dataDict objectForKey:@"au_name"]] addObject:foodDict];
            
        }

    }

Result:

 {
 "Arvind Kumar" =     (
                {
            "aef_food_category" = 4;
            "aef_id" = 9;
            "au_id" = 3;
        },
                {
            "aef_food_category" = 2;
            "aef_id" = 1;
            "au_id" = 3;
        }
    );
    abi =     (
                {
            "aef_food_category" = 1;
            "aef_id" = 6;
            "au_id" = 4;
        }
    );
    viswanathan =     (
                {
            "aef_food_category" = 2;
            "aef_id" = 3;
            "au_id" = 2;
        },
                {
            "aef_food_category" = 1;
            "aef_id" = 8;
            "au_id" = 2;
        },
                {
            "aef_food_category" = 4;
            "aef_id" = 10;
            "au_id" = 2;
        }
    );
}

// Table view

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return [[sections allKeys] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    
    return [[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [[self.sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    NSDictionary *book = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [book objectForKey:@"aef_id"];    
    cell.detailTextLabel.text = [book objectForKey:@"aef_food_category"];
    return cell;
}




Thursday, 26 November 2015

UILabel touch event

UILabel *label = [[UILabel alloc]init];
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =
      [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)];
[label addGestureRecognizer:tapGesture];

Monday, 23 November 2015

UIView With Multiple Colors iOS


-(void)drawRect:(CGRect)rect {
    CGRect upperRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height * .5);
    CGRect lowerRect = CGRectMake(rect.origin.x, rect.origin.y + (rect.size.height * .5), rect.size.width, rect.size.height *(1-.5));

    [[UIColor redColor] set];
    UIRectFill(upperRect);
    [[UIColor greenColor] set];
    UIRectFill(lowerRect);
}

Thursday, 19 November 2015

UIView transition animation


-(void)SwipeRight:(UIView *)view{
    
    CATransition* transition = [CATransition animation];
    [transition setDuration:0.5];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromRight;
    [transition setFillMode:kCAFillModeBoth];
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [view.layer addAnimation:transition forKey:kCATransition];
  
}

-(void)SwipeLeft:(UIView *)view{
    CATransition* transition = [CATransition animation];
    [transition setDuration:0.5];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    [transition setFillMode:kCAFillModeBoth];
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [view.layer addAnimation:transition forKey:kCATransition];

}

(OR)

- (void)slideView:(UIView*)view direction:(BOOL)isLeftToRight {
    CGRect frame = view.frame;
    frame.origin.x = (isLeftToRight) ? -
[[UIScreen mainScreen]bounds].size.width : 
[[UIScreen mainScreen]bounds].size.width;
    view.frame = frame;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    frame.origin.x = 0;
    view.frame = frame;
    [UIView commitAnimations];
}

Friday, 6 November 2015

custom button

UIViewController.h

#import "CustomView.h"

@interface ViewController : UIViewController<CustomViewDelegate>
@property (strong, nonatomic)IBOutlet CustomView *btn1;

@end

UIViewController.m

@interface ViewController ()
{
    dispatch_time_t popTime1;
    NSTimer * myTimer ;
}
@end

/*
//UIViewController you create customview as addsubview you will use initWithFrame.

-(void)loadView
{
    [super loadView];
    CustomView *view = [[CustomView alloc]initWithFrame:self.view.bounds];
    view.delegate = self;
    [self.view addSubview:view];
    
}
 */


-(void)sendButtonPressed{    
    [btn1 indicator];
   popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
    dispatch_after(popTime1, dispatch_get_main_queue(), ^(void){
        [btn1 resultSuccess];
    });
  myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(aTime) userInfo:nil repeats:YES];
}

-(void)aTime
{
    [myTimer invalidate];
    [btn1 saveBack];
}



UIView 
CustomView.h
@protocol CustomViewDelegate <NSObject>
-(void)sendButtonPressed;
@end

@interface CustomView : UIView
@property (assign) id<CustomViewDelegate> delegate;
//@property (strong, nonatomic) id<CustomViewDelegate> delegate;
@property (strong, nonatomic) UIButton* sendButton;
@property (strong, nonatomic) UIActivityIndicatorView *activityIndicator;
-(void)indicator;
-(void)resultSuccess;
-(void)saveBack;
@end

CustomView.m

/*
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
       // self.backgroundColor = [UIColor whiteColor];
[self btnview];
      }
    return self;
}
*/

-(void)btnview{
    sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sendButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [sendButton addTarget:self.delegate action:@selector(sendButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [sendButton setTitle:@"save" forState:UIControlStateNormal];
    [sendButton setBackgroundColor:[UIColor blueColor]];
    [self addSubview:sendButton];
}

//UIViewController you create customview as xib you will use awakeFromNib

- (void) awakeFromNib
{
    [self btnview];
}

-(void)indicator
{    
   activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityIndicator.alpha = 1.0;
    activityIndicator.center = CGPointMake(20,20);
    activityIndicator.hidesWhenStopped = NO;
    [sendButton addSubview:activityIndicator];
    [activityIndicator startAnimating];
    sendButton.userInteractionEnabled = NO;
}

-(void)resultSuccess{
    activityIndicator.hidesWhenStopped = YES;
    [activityIndicator stopAnimating];
    [sendButton setBackgroundColor:[UIColor grayColor]];
    [sendButton setTitle:@"success" forState:UIControlStateNormal];
    
    [UIView transitionWithView:sendButton duration:0.3 options:UIViewAnimationOptionTransitionFlipFromBottom|UIViewAnimationOptionCurveEaseInOut animations:^{
        [sendButton setAlpha:0.0];
        [sendButton setAlpha:1.0];
    } completion:^(BOOL finished){
       
    }];
   
}

-(void)saveBack{
    [sendButton setTitle:@"save" forState:UIControlStateNormal];
    [sendButton setBackgroundColor:[UIColor blueColor]];
    [UIView transitionWithView:sendButton duration:0.3 options:UIViewAnimationOptionTransitionFlipFromTop|UIViewAnimationOptionCurveEaseInOut animations:^{
        [sendButton setAlpha:0.0];
        [sendButton setAlpha:1.0];
    } completion:^(BOOL finished){
      sendButton.userInteractionEnabled = YES;
    }];
}

Tuesday, 6 October 2015

uitableview get indexpath to uibutton

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    AccessUsersCell *cell = (AccessUsersCell *) [tableView dequeueReusableCellWithIdentifier :CellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AccessUsersCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.btnSelect.tag = indexPath.row + 1;
        [cell.btnSelect addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return cell;

}


- (UITableViewCell *)containingCellForView:(UIView *)view
{
    if (!view.superview)
        return nil;

    if ([view.superview isKindOfClass:[UITableViewCell class]])
        return (UITableViewCell *)view.superview;

    return [self containingCellForView:view.superview];
}

- (void)buttonClicked:(id)sender
{
    UITableViewCell *containingCell = [self containingCellForView:sender];
    if (containingCell) {
        NSIndexPath *indexPath = [tableName indexPathForCell:containingCell];
        NSLog(@"Section: %i Row: %i", indexPath.section, indexPath.row);
    }
}

json convert to section table

Example:
json =  (
        {
        author = "Jeff Hawkins";
        description = "Jeff Hawkins;
        title = "On Intelligence";
    },
        {
        author = "Jack Kerouac";
        description = "The most;
        title = "On The Road";
    },
        {
        author = "Daniel Quinn";
        description = "Winner of the;
        title = Ishmael;
    },
        {
        author = "Frank Herbert";
        description = "This Hugo ;
        title = Dune;
    }
)

    NSMutableArray *books;

    NSMutableDictionary *sections;

//after return json value

self.sections = [[NSMutableDictionary alloc] init];
    
    BOOL found;
    
    // Loop through the books and create our keys
    for (NSDictionary *book in self.books)
    {        
        NSString *c = [[book objectForKey:@"title"] substringToIndex:1];
        
        found = NO;
        
        for (NSString *str in [self.sections allKeys])
        {
            if ([str isEqualToString:c])
            {
                found = YES;
            }
        }
        
        if (!found)
        {     
            [self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
        }
    }
        
    // Loop again and sort the books into their respective keys
    for (NSDictionary *book in self.books)
    {
        [[self.sections objectForKey:[[book objectForKey:@"title"] substringToIndex:1]] addObject:book];
    }    
    
  // Sort each section array
    for (NSString *key in [self.sections allKeys])
    {
        [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES]]];

    } 
// Table view

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return [[self.sections allKeys] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    
    return [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
}

//Search array for section side bar
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    NSDictionary *book = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [book objectForKey:@"title"];    
    cell.detailTextLabel.text = [book objectForKey:@"description"];
    return cell;
}


Result:

Monday, 21 September 2015

json string send to server

Objective c:

 NSString *jsonString;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mutablearray
                                                       options:NSJSONWritingPrettyPrinted 
                                                         error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString  = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        

    }

eg:

NSDictionary  *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                // Object and key pairs
                firstName, @"fname",
                lastName, @"lname",
                phoneNumStr, @"phone_no",
                emailStr, @"email_id",
                nil];

        [allObjectArray addObject:dict];

php:

$json_str = $_POST['jsonstring'];

$contact_details = json_decode($json_str);
   
      foreach($contact_details as $key => $value)
      {
  $fname = $value->fname;
  $lname = $value->lname;
  $email = $value->email_id;
  $phone = $value->phone_no;

//insert or update query
}

Friday, 11 September 2015

Check If column already exist and if not Alter Table in sqlite

-(BOOL)checkColumnExists
{
    BOOL columnExists = NO;

    sqlite3_stmt *selectStmt;

    const char *sqlStatement = "select yourcolumnname from yourtablename";
    if(sqlite3_prepare_v2(yourDbHandle, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK)
        columnExists = YES;

    return columnExists;
}

Monday, 31 August 2015

Image comparison

  UIImage *image1 = [UIImage imageNamed:@"EmptyLike"];
    UIImage *image2 = [button_image imageForState:UIControlStateNormal];
    
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);


    if ([data1 isEqualToData:data2]) {

}

Saturday, 29 August 2015

Change NSDictionary with NSMutableArray value

   NSMutableDictionary *newDict = [[NSMutableDictionary alloc]init];
    NSDictionary *oldDict = (NSDictionary *)[groupsArr objectAtIndex:selectrow];
    [newDict addEntriesFromDictionary:oldDict];
    [newDict setObject:note.object forKey:groupName];
    [groupsArr replaceObjectAtIndex:selectrow withObject:newDict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:selectrow inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];

    [self.GroupsTable reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

Use the object property of NSNotificationcenter

 NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              PhoneNoTxtField.text, @"phone",
                              EmailTxtField.text, @"email",
                              nil];        
 [[NSNotificationCenter defaultCenter] postNotificationName:@"phone_email"
                                                            object:self

                                                          userInfo:dict]; 


  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPhoneEmail:) name:@"phone_email" object:nil];

- (void)addPhoneEmail:(NSNotification *)notification {    
    NSLog(@"email: %@",[notification.userInfo objectForKey:@"email"]);
    NSLog(@"phone: %@",[notification.userInfo objectForKey:@"phone"]);
}

(OR)

[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTable" object:self.TxtGroupName.text];


 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rightMenuaction:) name:@"reloadTable" object:nil];

-(void)rightMenuaction:(NSNotification *)note
{
      NSLog(@"reload table %@",note.object);
}

Friday, 28 August 2015

NSMutableArray convert to jsonString

   NSString *jsonString;
   NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:nsmutablearray
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString  = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        

    }


Thursday, 27 August 2015

NSMutableString add NSString

NSMutableString *address = [[NSMutableString alloc]init];
 
            if (![[jsonObjects objectForKey:@"city"] isEqualToString:@""]){
                if (address.length != 0){
                    [address appendString:@","];
                }
                [address appendString:[jsonObjects objectForKey:@"city"]];
            }

string convert to json

 NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSData *objectData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers
                                                               error:nil];
        
        NSString *strStatus =[NSString stringWithFormat:@"%@",[json objectForKey:@"Status"]];
        NSString *strMessage = [NSString stringWithFormat:@"%@",[json objectForKey:@"Message"]];

        strReg_id = [NSString stringWithFormat:@"%@",[json objectForKey:@"Regid"]];

Wednesday, 26 August 2015

Phone number format

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSString *decimalString = [components componentsJoinedByString:@""];

    NSUInteger length = decimalString.length;
    BOOL hasLeadingOne = length > 0 && [decimalString characterAtIndex:0] == '1';

    if (length == 0 || (length > 10 && !hasLeadingOne) || (length > 11)) {
        textField.text = decimalString;
        return NO;
    }

    NSUInteger index = 0;
    NSMutableString *formattedString = [NSMutableString string];

    if (hasLeadingOne) {
        [formattedString appendString:@"1 "];
        index += 1;
    }

    if (length - index > 3) {
        NSString *areaCode = [decimalString substringWithRange:NSMakeRange(index, 3)];
        [formattedString appendFormat:@"(%@) ",areaCode];
        index += 3;
    }

    if (length - index > 3) {
        NSString *prefix = [decimalString substringWithRange:NSMakeRange(index, 3)];
        [formattedString appendFormat:@"%@-",prefix];
        index += 3;
    }

    NSString *remainder = [decimalString substringFromIndex:index];
    [formattedString appendString:remainder];

    textField.text = formattedString;

    return NO;
}

(OR)

 [self.textField addTarget:self action:@selector(formatPhoneNumber) forControlEvents:UIControlEventEditingChanged];


#pragma mark - phone number formatting

- (void)formatPhoneNumber {
    
    NSString *currentString = self.textField.text;
    NSString *strippedValue = [currentString stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, currentString.length)];

    NSString *formattedString;
    if (strippedValue.length == 0) {
        formattedString = @"";
    }
    else if (strippedValue.length < 3) {
        formattedString = [NSString stringWithFormat:@"(%@", strippedValue];
    }
    else if (strippedValue.length == 3) {
        formattedString = [NSString stringWithFormat:@"(%@) ", strippedValue];
    }
    else if (strippedValue.length < 6) {
        formattedString = [NSString stringWithFormat:@"(%@) %@", [strippedValue substringToIndex:3], [strippedValue substringFromIndex:3]];
    }
    else if (strippedValue.length == 6) {
        formattedString = [NSString stringWithFormat:@"(%@) %@-", [strippedValue substringToIndex:3], [strippedValue substringFromIndex:3]];
    }
    else if (strippedValue.length <= 10) {
        formattedString = [NSString stringWithFormat:@"(%@) %@-%@", [strippedValue substringToIndex:3], [strippedValue substringWithRange:NSMakeRange(3, 3)], [strippedValue substringFromIndex:6]];
    }
    else if (strippedValue.length >= 11) {
        formattedString = [NSString stringWithFormat:@"(%@) %@-%@ x%@", [strippedValue substringToIndex:3], [strippedValue substringWithRange:NSMakeRange(3, 3)], [strippedValue substringWithRange:NSMakeRange(6, 4)], [strippedValue substringFromIndex:10]];
    }
    
    self.textField.text = formattedString;
}

Tuesday, 25 August 2015

Image upload with parameters

- (void) pushView {
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:today];
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize = 250*1024;
    
    NSData *imageData = UIImageJPEGRepresentation(snap.image, compression);
    
    while ([imageData length] > maxFileSize && compression > maxCompression)
    {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(snap.image, compression);
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@/ChatImageMucUpload_android.php",kBaseURL];

    NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:encodedString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    //date parameter
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"sImageUploadDate\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[dateString dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //userid parameter
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"sEventId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[self.sEventid dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //eventid parameter
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"sCreatorId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[self.sUserid dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    // close form
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    [request setHTTPBody:body];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    //NSLog(@"return : %@", returnString);
    
    if([returnString isEqualToString:@"2"]){
           NSLog(@"not save");

    }else{
          NSLog(@"save");
  }


php

//  database connection
require_once('DataBaseConnection.php');


$strCreatorId = mysql_real_escape_string($_POST['sCreatorId']);
$strEventId = mysql_real_escape_string($_POST['sEventId']);
$strImageUploadDate = mysql_real_escape_string($_POST['sImageUploadDate']);
if (isset($_POST['sCreatorId'])) {
$picnew_id =mysql_result(mysql_query("Select Max(eg_image_id)+1 as MaxID from eaa_gallery"),0,"MaxID");

$uploaddir = $imgurl.'Gallery/';
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;

$extension = ".".pathinfo($uploadFile, PATHINFO_EXTENSION);

$randomNumber = "img0".$sslocatID."PD".$picnew_id;
$newName = $uploadDir . $randomNumber;

if ($_FILES['userfile']['size']> 3000000) {
exit("Your file is too large."); 
}
$imageurl = 'Gallery/EventId_'.$strEventId;
if (!file_exists($imageurl)) {
$location = mkdir($imageurl, 0777, true);
}
$imageurl1 = $imageurl.'/'.$newName.$extension;
mysql_query('SET CHARACTER SET utf8');
$strSQL = "INSERT INTO eaa_gallery (eg_event_id, eg_event_creatore_id, eg_image_url, eg_upload_date, eg_status)
VALUES ('".$strEventId."','".$strCreatorId."','".$imageurl1."','".$strImageUploadDate."', 1)";

$objQuery = mysql_query($strSQL);
$arr = null;

if(!$objQuery)
{
$arr = 0;
}
else{
if (move_uploaded_file($_FILES['userfile']['tmp_name'],$imageurl1)) {

/////
$fileSize = filesize($imageurl1);

$path_to_image = $imageurl."/".$newName. $extension; //give the name of image here after slash
                 $path_to_thumbnail = $imageurl."/thumbs/".$newName;
if (!file_exists($imageurl."/thumbs/")) {
$location1 = mkdir($imageurl."/thumbs/", 0777, true);
}

                 resize(100,$path_to_thumbnail, $path_to_image);

//createThumbs($imageurl."/",$imageurl."/thumbs/",$newName);

//$arr = $imageurl1;
$arr = $imageurl."/thumbs/".$newName.$extension."-->".$fileSize;
// moving image
}else{
$arr = 2;
// Not moving
}
}
echo json_encode($arr);
mysql_close($objConnect);
}



 function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);

$black = imagecolorallocate($im, 0, 0, 0);

    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);

// Make the background transparent
imagecolortransparent($tmp, $black);

    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp, "$targetFile.$new_image_ext");
}