Friday, May 8, 2015

Using Blocks:


#import <Foundation/Foundation.h>

typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end

@implementation SampleClass

- (void)performActionWithCompletion:(CompletionBlock)completionBlock{

    NSLog(@"Action Performed");
    completionBlock();
}

@end

int main()
{
    /* my first program in Objective-C */
    SampleClass *sampleClass = [[SampleClass alloc]init];
    [sampleClass performActionWithCompletion:^{
        NSLog(@"Completion is called to intimate action is performed.");
    }];
   
    return 0;
}



Declaring String Constants:



If they are specific and internal to a single class, declare them as static const at the top of the .m file, like so:

static NSString *const MyThingNotificationKey = @"MyThingNotificationKey";


====================================================================


If they pertain to a single class but should be public/used by other classes, declare them as extern in the header and define them in the .m:

//.h
extern NSString *const MyThingNotificationKey;

//.m
NSString *const MyThingNotificationKey = @"MyThingNotificationKey";

Detect screenshots in Objective C:


NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
              object:nil
               queue:mainQueue
          usingBlock:^(NSNotification *note) {
             // executes after screenshot
          }];
         
         

Base64 Encoding and Decoding in iOS 7.0:


NSString *plainString = @"foo";

Encoding:
---------
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v


Decoding:
---------
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo

Wednesday, April 29, 2015

HTML Table DOM:


var table = document.getElementsByTagName("Table");

var result = table[0];
var len = result.rows.length;

for(var i=1; i < len; i++){
  //console.log(row);
  var emailId = result.rows[i].cells[1].innerHTML;
  console.log(emailId);
}

Monday, April 27, 2015

Script to extract emails from WebPage:


var text = document.body.innerHTML;
function extractEmails (text)
{
    return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}

document.write(extractEmails(text).join('
'));

alert(extractEmails(text).join('\n'));


Cell Separator Inset:



For iOS 7.0:
============

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

or

[tableView setSeparatorInset:UIEdgeInsetsZero];
   
   
For iOS 8.0:
============

tableView.layoutMargins = UIEdgeInsetsZero;
cell.layoutMargins = UIEdgeInsetsZero;


======================================================


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
           [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

Thursday, March 26, 2015

Adding Custom Gradient to Button:


-(CAGradientLayer *)getCAGradientLayerWithFrame : (CGRect)bounds {
  CAGradientLayer *gradientLayer = [CAGradientLayer layer];
 
  bounds.origin.y    = bounds.size.height - 6;
  bounds.size.height = 6;

  gradientLayer.frame = bounds;
  gradientLayer.colors = [NSArray arrayWithObjects:
                          (id)[UIColor orangeColor].CGColor,
                          (id)[UIColor orangeColor].CGColor,
                          nil];
 
  gradientLayer.locations = [NSArray arrayWithObjects:
                             [NSNumber numberWithFloat:0.0f],
                             [NSNumber numberWithFloat:1.0f],
                             nil];

  return gradientLayer;
}




- (IBAction)btnAction:(id)sender {
 
  UIButton *btn = (UIButton *)sender;
  NSArray *subLayersArr = [btn.layer sublayers];
 
  NSLog(@"subLayersArr : %@", subLayersArr);
 
 
  CAGradientLayer *subLayer = nil;
  if ([subLayersArr count]) {
    subLayer = [subLayersArr objectAtIndex:0];
  }
 
  NSLog(@"subLayer : %@", subLayer);
 
 
  btn.selected = !btn.selected;

  if (btn.selected) {
    subLayer.hidden = NO;
  } else {
    subLayer.hidden = YES;
  }
 
}


Usage:
=====
CAGradientLayer *layer = [self getCAGradientLayerWithFrame:self.aButton.layer.bounds];
self.aButton.backgroundColor = [UIColor yellowColor];
[self.aButton.layer addSublayer:layer];





Tuesday, March 24, 2015

Hide StatusBar in iOS


UIStatusBarHidden

UIViewControllerBasedStatusBarAppearance

Custom SplitViewController:



- (void)viewDidLayoutSubviews
{
  [super viewDidLayoutSubviews];
 
  //NSLog(@"CustomSplitViewController is called"); 260, 764
 
  const CGFloat kMasterViewWidth = 260.0;
 
  float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
 
  NSLog(@"systemVersion : %0.2f", systemVersion);
 
 
  if(systemVersion < 8.0f){
  
      UIViewController *masterViewController = [self.viewControllers objectAtIndex:0];
      UIViewController *detailViewController = [self.viewControllers objectAtIndex:1];
    
      if (detailViewController.view.frame.origin.x > 0.0) {
        // Adjust the width of the master view
        CGRect masterViewFrame = masterViewController.view.frame;
        CGFloat deltaX = masterViewFrame.size.width - kMasterViewWidth;
        masterViewFrame.size.width -= deltaX;
        masterViewController.view.frame = masterViewFrame;
      
        // Adjust the width of the detail view
        CGRect detailViewFrame = detailViewController.view.frame;
        detailViewFrame.origin.x -= deltaX;
        detailViewFrame.size.width += deltaX;
        detailViewController.view.frame = detailViewFrame;
      
        [masterViewController.view setNeedsLayout];
        [detailViewController.view setNeedsLayout];
      }
  
  } else {
  
    self.maximumPrimaryColumnWidth = kMasterViewWidth;
  
  }
 
 
}



Thursday, February 26, 2015

NSDataDetector Example:


NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];

NSString *stringValue =  @"Two links: useyourloaf.com and apple.com";
NSURL *url = nil;
NSTextCheckingResult *result = [detector firstMatchInString:stringValue
                                                    options:0
                                                      range:NSMakeRange(0, stringValue.length)];
if (result.resultType == NSTextCheckingTypeLink)
{
    url = result.URL;
}
NSLog(@"matched: %@", url);
// matched: http://useyourloaf.com

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

NSString *stringValue = @"Two links: useyourloaf.com and apple.com";   
[detector enumerateMatchesInString:stringValue
                           options:0
                             range:NSMakeRange(0, stringValue.length)
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
    if (result.resultType == NSTextCheckingTypeLink)
    {
        NSLog(@"matched: %@",result.URL);
    }        
}];
// matched: http://useyourloaf.com
// matched: http://apple.com


//====================================================================

NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
  if ([match resultType] == NSTextCheckingTypeLink) {
    NSURL *url = [match URL];
    NSLog(@"found URL: %@", url);
  }
}


//====================================================================


Sunday, January 25, 2015

HTML Options Looping


var aa = document.getElementById("Criteria_FlightNo");
var str = "{";
for(var i=0; i < aa.options.length; i++){
  str += "\"" + aa.options[i].value + "\"" +  ":" + "\"" + aa.options[i].innerHTML + "\"";
  if(i!= aa.options.length-1){
    str += ",";
  }
}
str += "}";
console.log(str);

 

Wednesday, December 31, 2014

Core Graphics Drawing



1.)Drawing a Line Segment
----------------------------------
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextMoveToPoint(context, 50, 200);
CGContextAddLineToPoint(context,100,100);
CGContextMoveToPoint(context, 50, 200);
CGContextAddLineToPoint(context,200,400);
CGContextStrokePath(context);


2.)Drawing a Filled Circle
--------------------------------
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(contextRef, 255, 0, 255, 0.9);
CGContextSetRGBStrokeColor(contextRef, 255, 0, 0, 0.9);
CGContextFillEllipseInRect(contextRef, CGRectMake(100, 100, 50, 50));


3.)Drawing a Hollow Circle
----------------------------------
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(contextRef, 255, 0, 255, 0.9);
CGContextSetRGBStrokeColor(contextRef, 255, 0, 0, 0.9);
CGContextStrokeEllipseInRect(contextRef, CGRectMake(200, 100, 50, 50));


4.)Drawing a circle with boundary
------------------------------------------
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 0, 255, 0, 1);
CGContextFillEllipseInRect(context, CGRectMake(100, 200, 25, 25));
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextStrokeEllipseInRect(context,CGRectMake(100, 200, 25, 25));


5.)Drawing a Hollow Rectangle
---------------------------------------
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 255, 255, 0, 1);
CGContextStrokeRect(ctx, CGRectMake(195, 195, 60, 60));


6.)Drawing a Solid Rectangle
------------------------------------
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(ctx, 255, 255, 0, 1);
CGContextFillRect(ctx, CGRectMake(260, 195, 60, 60));


7.)Drawing a Triangle
----------------------------
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 255, 0, 255, 1);
CGPoint points[6] = { CGPointMake(200, 200), CGPointMake(250, 250),
CGPointMake(250, 250), CGPointMake(100, 250),
CGPointMake(100, 250), CGPointMake(200, 200) };
CGContextStrokeLineSegments(ctx, points, 6);







Tuesday, December 30, 2014

Resize Image using ImageIO.framework


-(UIImage*)resizeImageToMaxSize:(CGFloat)max
{
    CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], NULL);
    if (!imageSource)
        return nil;

    CFDictionaryRef options = (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
        (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform,
        (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent,
        (id)[NSNumber numberWithFloat:max], (id)kCGImageSourceThumbnailMaxPixelSize,
        nil];
    CGImageRef imgRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);

    UIImage* scaled = [UIImage imageWithCGImage:imgRef];

    CGImageRelease(imgRef);
    CFRelease(imageSource);

    return scaled;
}

Blocks in UITableViewCell


@interface MyTableViewCell

@property(nonatomic, copy) void (^checkboxHandler)(void);

@end


@implementation MyTableViewCell

- (IBAction)checkboxPressed:(UIButton *)sender {
self.checkboxHandler();
}

@end



@implementation MyTableViewController

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"cell"
    forIndexPath:indexPath;
    cell.checkboxHandler = ^{
    // Perform the desired work in response to checkbox
    };
    return cell;
}

@end


ImageIO.framework Example

#import <ImageIO/ImageIO.h>

NSURL *imageFileURL = [NSURL fileURLWithPath:...];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
if (imageSource == NULL) {
    // Error loading image
    ...
    return;
}

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache,
                         nil];
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (CFDictionaryRef)options);
if (imageProperties) {
    NSNumber *width = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
    NSNumber *height = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
    NSLog(@"Image dimensions: %@ x %@ px", width, height);
    CFRelease(imageProperties);
}
CFRelease(imageSource);

========================================================

CFDictionaryRef exif = CFDictionaryGetValue(imageProperties, kCGImagePropertyExifDictionary);
if (exif) {
  NSString *dateTakenString = (NSString *)CFDictionaryGetValue(exif, kCGImagePropertyExifDateTimeOriginal);
  NSLog(@"Date Taken: %@", dateTakenString);
}

CFDictionaryRef tiff = CFDictionaryGetValue(imageProperties, kCGImagePropertyTIFFDictionary);
if (tiff) {
    NSString *cameraModel = (NSString *)CFDictionaryGetValue(tiff, kCGImagePropertyTIFFModel);
    NSLog(@"Camera Model: %@", cameraModel);
}

CFDictionaryRef gps = CFDictionaryGetValue(imageProperties, kCGImagePropertyGPSDictionary);
if (gps) {
    NSString *latitudeString = (NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLatitude);
    NSString *latitudeRef = (NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLatitudeRef);
    NSString *longitudeString = (NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLongitude);
    NSString *longitudeRef = (NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLongitudeRef);
    NSLog(@"GPS Coordinates: %@ %@ / %@ %@", longitudeString, longitudeRef, latitudeString, latitudeRef);
}


=======================================================

Date Taken: 2011:03:27 11:30:30
Camera Model: Canon EOS 20D
GPS Coordinates: 8.374788 E / 54.89472 N



Wednesday, December 24, 2014

Round two corners of UIView


-(void) setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners withRadius:(CGFloat)radius;
{
    UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer* shape = [[CAShapeLayer alloc] init];
    [shape setPath:rounded.CGPath];

    view.layer.mask = shape;
}


[self setMaskTo:view1 byRoundingCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft withRadius:20.0];

CABasicAnimation Examples



UIView *AnimView1=[[UIView alloc] initWithFrame:CGRectMake(30, 50, 50, 50)];
AnimView1.backgroundColor=[UIColor greenColor];
[self.view addSubview:AnimView1];

UIView *AnimView2=[[UIView alloc] initWithFrame:CGRectMake(90, 75, 50, 50)];
AnimView2.backgroundColor=[UIColor orangeColor];
[self.view addSubview:AnimView2];

UIView *AnimView3=[[UIView alloc] initWithFrame:CGRectMake(170, 90, 50, 50)];
AnimView3.backgroundColor=[UIColor yellowColor];
[self.view addSubview:AnimView3];

UIView *AnimView4=[[UIView alloc] initWithFrame:CGRectMake(240, 150, 50, 50)];
AnimView4.backgroundColor=[UIColor blueColor];
[self.view addSubview:AnimView4];

//shrink
CABasicAnimation* shrink = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
shrink.toValue = [NSNumber numberWithDouble:0.5];
shrink.duration = 0.5;
shrink.delegate = self;
shrink.repeatCount=INFINITY;
shrink.autoreverses=YES;
[[AnimView1 layer] addAnimation:shrink forKey:@"shrinkAnim"];

//moving
CABasicAnimation *Animation1;
Animation1=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
Animation1.duration=0.2;
Animation1.repeatCount=INFINITY;
Animation1.autoreverses=YES;
Animation1.fromValue=[NSNumber numberWithFloat:0];
Animation1.toValue=[NSNumber numberWithFloat:-10];
[[AnimView2 layer] addAnimation:Animation1 forKey:@"shakeAnim"];

//rotating
CABasicAnimation *Animation2;
Animation2=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
Animation2.duration=0.2;
Animation2.repeatCount=INFINITY;
Animation2.autoreverses=YES;
Animation2.fromValue=[NSNumber numberWithFloat:0];
Animation2.toValue=[NSNumber numberWithFloat:M_PI/4];
[[AnimView3 layer] addAnimation:Animation2 forKey:@"rotateAnim"];

//fade
CABasicAnimation *animation3 = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation3.duration=0.5;
animation3.repeatCount=INFINITY;
animation3.autoreverses=YES;
animation3.fromValue=[NSNumber numberWithFloat:1];
animation3.toValue=[NSNumber numberWithFloat:0];
[[AnimView4 layer] addAnimation:animation3 forKey:@"fadeAnim"]; 


Highlight Text in UIWebView using JavaScript:


[webView stringByEvaluatingJavaScriptFromString:@"var range = window.getSelection().getRangeAt(0);"
    @"var selectionContents = range.extractContents();"
    @"var span = document.createElement('span');"
    @"span.style.backgroundColor = 'yellow';"
    @"span.appendChild(selectionContents);"
    @"range.insertNode(span)" ];


Text field accept user required characters only


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    NSString *acceptedCharacters=@"AEIOU12345"; // only these characters  will be allowed to be displayed in text filed.
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedCharacters] invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    return [string isEqualToString:filtered];
}