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];
}


Taking screenshot programmatically in iOS 7



UIScreen *screen = [UIScreen mainScreen] ;
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];

UIView *view = [screen snapshotViewAfterScreenUpdates:YES];

UIGraphicsBeginImageContextWithOptions(screen.bounds.size, NO, 0);
[keyWindow drawViewHierarchyInRect:keyWindow.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *data= UIImagePNGRepresentation(image);
[data writeToFile:[NSString stringWithFormat:@"%@/ScreenShot.png",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]] atomically:YES];



UIActivityIndicatorView at the Center of View with AutoLayout



UIActivityIndicatorView at the Center of View with AutoLayout


 UIActivityIndicatorView  *spinner;
spinner =[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setTranslatesAutoresizingMaskIntoConstraints:NO];
spinner.color=[UIColor blackColor];
    [self.view addSubview:spinner];

 NSLayoutConstraint *cont = [NSLayoutConstraint constraintWithItem:spinner attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
    [self.view addConstraint:cont];

 cont = [NSLayoutConstraint constraintWithItem:spinner attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];

    [self.view addConstraint:cont];

Display HTML with NSAttributedString



NSString *html = @"Wow! Now iOS can create

NSAttributedString

from HTMLs!";
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};

NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];

NSData *htmlData = [attrString dataFromRange:NSMakeRange(0, [attrString length]) documentAttributes:options error:nil];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];

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


NSString *htmlString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                 options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                           NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                      documentAttributes:nil error:nil];
                     
                     

Detect blinks and smiles with CoreImage


UIImage *image = [UIImage imageNamed:@"myImage"];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                          context:nil
                                          options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];

NSDictionary *options = @{ CIDetectorSmile: @YES, CIDetectorEyeBlink: @YES };

NSArray *features = [detector featuresInImage:image.CIImage options:options];

for (CIFaceFeature *feature in features) {
    NSLog(@"Bounds: %@", NSStringFromCGRect(feature.bounds));

    if (feature.hasSmile) {
    NSLog(@"Nice smile!");
    } else {
    NSLog(@"Why so serious?");
    }
    if (feature.leftEyeClosed || feature.rightEyeClosed) {
    NSLog(@"Open your eyes!");
    }
}

Base64 Encoding and Decoding



NSData* sampleData = [@"Some sample data" dataUsingEncoding:NSUTF8StringEncoding];


Base64 Encoding:
================
NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
NSLog(@"Base64-encoded string is %@", base64String); // prints "U29tZSBzYW1wbGUgZGF0YQ=="


Base64 Decoding:
================
NSData* dataFromString = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSLog(@"String is %@",[NSString stringWithUTF8String:[dataFromString bytes]]); // prints "Some sample data"

Blur Effect using CoreImage


Add CoreImge.framework


UIImage *theImage = [UIImage imageNamed:@"Sample.png"];

    //create our blurred image
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [CIImage imageWithCGImage:theImage.CGImage];

    //setting up Gaussian Blur (we could use one of many filters offered by Core Image)
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithFloat:15.0f] forKey:@"inputRadius"];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    //CIGaussianBlur has a tendency to shrink the image a little, this ensures it matches up exactly to the bounds of our original image
    CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];

self.imageView.image=[UIImage imageWithCGImage:cgImage];

CoreImage Filters


First you need to import and link with the CoreImage.framework

UIImage* inputImage = [UIImage imageNamed:@"image.jpg"];
CIImage* filterInputImage = [CIImage imageWithCGImage:inputImage.CGImage];

CIFilter* filter = [CIFilter filterWithName:@"CIDotScreen"];
[filter setValue:filterInputImage forKey:kCIInputImageKey];

CIImage* filterOutputImage = filter.outputImage;

To make it back into a UIImage, a CIContext needs to be used, as so

CIContext* ctx = [CIContext contextWithOptions:nil];
CGImageRef createdImage = [ctx createCGImage:filterOutputImage fromRect:filterOutputImage.extent];

UIImage* outputImage = [UIImage imageWithCGImage:createdImage];

CGImageRelease(createdImage);
createdImage = nil;


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

NSLog(@"%@", [CIFilter filterNamesInCategory:kCICategoryBuiltIn]);

(
    CIAdditionCompositing,
    CIAffineClamp,
    CIAffineTile,
    CIAffineTransform,
    CIBarsSwipeTransition,
    CIBlendWithMask,
    CIBloom,
    CIBumpDistortion,
    CIBumpDistortionLinear,
    CICheckerboardGenerator,
    CICircleSplashDistortion,
    CICircularScreen,
    CIColorBlendMode,
    CIColorBurnBlendMode,
    CIColorControls,
    CIColorCube,
    CIColorDodgeBlendMode,
    CIColorInvert,
    CIColorMap,
    CIColorMatrix,
    CIColorMonochrome,
    CIColorPosterize,
    CIConstantColorGenerator,
    CICopyMachineTransition,
    CICrop,
    CIDarkenBlendMode,
    CIDifferenceBlendMode,
    CIDisintegrateWithMaskTransition,
    CIDissolveTransition,
    CIDotScreen,
    CIEightfoldReflectedTile,
    CIExclusionBlendMode,
    CIExposureAdjust,
    CIFalseColor,
    CIFlashTransition,
    CIFourfoldReflectedTile,
    CIFourfoldRotatedTile,
    CIFourfoldTranslatedTile,
    CIGammaAdjust,
    CIGaussianBlur,
    CIGaussianGradient,
    CIGlideReflectedTile,
    CIGloom,
    CIHardLightBlendMode,
    CIHatchedScreen,
    CIHighlightShadowAdjust,
    CIHoleDistortion,
    CIHueAdjust,
    CIHueBlendMode,
    CILanczosScaleTransform,
    CILightenBlendMode,
    CILightTunnel,
    CILinearGradient,
    CILineScreen,
    CILuminosityBlendMode,
    CIMaskToAlpha,
    CIMaximumComponent,
    CIMaximumCompositing,
    CIMinimumComponent,
    CIMinimumCompositing,
    CIModTransition,
    CIMultiplyBlendMode,
    CIMultiplyCompositing,
    CIOverlayBlendMode,
    CIPinchDistortion,
    CIPixellate,
    CIRadialGradient,
    CIRandomGenerator,
    CISaturationBlendMode,
    CIScreenBlendMode,
    CISepiaTone,
    CISharpenLuminance,
    CISixfoldReflectedTile,
    CISixfoldRotatedTile,
    CISmoothLinearGradient,
    CISoftLightBlendMode,
    CISourceAtopCompositing,
    CISourceInCompositing,
    CISourceOutCompositing,
    CISourceOverCompositing,
    CIStarShineGenerator,
    CIStraightenFilter,
    CIStripesGenerator,
    CISwipeTransition,
    CITemperatureAndTint,
    CIToneCurve,
    CITriangleKaleidoscope,
    CITwelvefoldReflectedTile,
    CITwirlDistortion,
    CIUnsharpMask,
    CIVibrance,
    CIVignette,
    CIVortexDistortion,
    CIWhitePointAdjust
)


Interactive Notifications in iOS 8


In iOS 8 developers can now present interactive notifications in their apps.

To do so, first you need to register all possible notification “categories”. A category is defined by a set of actions. In my example I’m going to setup a category with reply and delete actions

Each action is shown to the user as a button. Actions have two possible activation modes: foreground or background. If your app can perform the action with no further interaction from the user then you want to use the background activation mode. If the action needs further user input then you can set the activation mode to foreground to have your app launched when actioned, for example, presenting a keyboard in your app when they reply button is tapped.




UIMutableUserNotificationAction* deleteAction = [[UIMutableUserNotificationAction alloc] init];
[deleteAction setIdentifier:@"delete_action_id"];
[deleteAction setTitle:@"Delete"];
[deleteAction setActivationMode:UIUserNotificationActivationModeBackground];
[deleteAction setDestructive:YES];

UIMutableUserNotificationAction* replyAction = [[UIMutableUserNotificationAction alloc] init];
[replyAction setIdentifier:@"reply_action_id"];
[replyAction setTitle:@"Reply"];
[replyAction setActivationMode:UIUserNotificationActivationModeForeground];
[replyAction setDestructive:NO];

UIMutableUserNotificationCategory* deleteReplyCategory = [[UIMutableUserNotificationCategory alloc] init];
[deleteReplyCategory setIdentifier:@"custom_category_id"];
[deleteReplyCategory setActions:@[replyAction, deleteAction] forContext:UIUserNotificationActionContextDefault];


NSSet* categories = [NSSet setWithArray:@[deleteReplyCategory]];
UIUserNotificationSettings* settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];


Now we can schedule a notification to use the previously setup category. This is the string identifier from before. This notification is scheduled after 10 seconds.

UILocalNotification* notification = [[UILocalNotification alloc] init];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:10]];
[notification setAlertBody:@"Somebody sent you a message"];
[notification setCategory:@"custom_category_id"];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];


When the user selects an option we get a callback to the app delegate.


- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler
{
    if([notification.category isEqualToString:@"custom_category_id"])
    {
        if([identifier isEqualToString:@"delete_action_id"])
        {
            NSLog(@"Delete was pressed");
        }
        else if([identifier isEqualToString:@"reply_action_id"])
        {
            NSLog(@"Reply was pressed");
        }
    }
   
    //    Important to call this when finished
    completionHandler();
}






-viewWillAppear in iOS 7.0



- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    const BOOL isInteractivePop = (self.navigationController.interactivePopGestureRecognizer.state == UIGestureRecognizerStateBegan);

    if(isInteractivePop)
    {
        //    Interactive pop stuff
    }
    else
    {
        //    Back button stuff
    }
}

iOS7 interactivePopGestureRecognizer for UINavigationController with hidden navigation bar

iOS7 introduces interactivePopGestureRecognizer property which is used for popping current view controller stack by a gesture (swipe right gesture from left edge as default). However if the navigation bar is hidden or the app uses a custom back button for navigation bar, this feature will not work. A bit lines of code can make this feature works again for those cases. In viewDidLoad() of view controller (or application:didFinishLaunchingWithOptions: of AppDelegate), we set the interactivePopGestureRecognizer.delegate to nil as below:

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
  self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}


interactivePopGestureRecognizer in UINavigationController



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Disable iOS 7 back gesture
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    // Enable iOS 7 back gesture
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return NO;
}

Tuesday, December 23, 2014

iPhone UI Designs Tips:


http://www.lovelyui.com/

http://www.mobile-patterns.com/

http://www.pttrns.com/

Cocoapods


Installing/Updating Cocoapods on MacOSX:
=======================================
$sudo gem install cocoapods

$sudo gem update --system



Using Cocoapods:
================
1. Create a 'Podfile' and store in xcode project root folder
2. Write pod '{pod_module}' in the created Podfile.
3. Then from the Terminal command line execute the file as
    $pod install
4. The above command will create an ProjectName.xworkspace file. Use that file instead of ProjectName.xcodeproj file.


  
Contents of Podfile:
====================
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

pod 'AFNetworking', '~> 2.0'
pod 'ARAnalytics', '~> 2.7'


#import <Reachability/Reachability.h>

QRCode Generator


- (void)setUIElementsAsEnabled:(BOOL)enabled
{
    self.generateButton.enabled = enabled;
    self.stringTextField.enabled = enabled;
}

- (CIImage *)createQRForString:(NSString *)qrString
{
    // Need to convert the string to a UTF-8 encoded NSData object
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];

    // Create the filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];

    // Send the image back
    return qrFilter.outputImage;
}


- (UIImage *)createNonInterpolatedUIImageFromCIImage:(CIImage *)image withScale:(CGFloat)scale
{
    // Render the CIImage into a CGImage
    CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:image fromRect:image.extent];

    // Now we'll rescale using CoreGraphics
    UIGraphicsBeginImageContext(CGSizeMake(image.extent.size.width * scale, image.extent.size.width * scale));
    CGContextRef context = UIGraphicsGetCurrentContext();
    // We don't want to interpolate (since we've got a pixel-correct image)
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
    // Get the image out
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // Tidy up
    UIGraphicsEndImageContext();
    CGImageRelease(cgImage);
    return scaledImage;
}


- (IBAction)handleGenerateButtonPressed:(id)sender {
    // Disable the UI
    [self setUIElementsAsEnabled:NO];
    [self.stringTextField resignFirstResponder];

    // Get the string
    NSString *stringToEncode = self.stringTextField.text;

    // Generate the image
    CIImage *qrCode = [self createQRForString:stringToEncode];

    // Convert to an UIImage
    UIImage *qrCodeImg = [self createNonInterpolatedUIImageFromCIImage:qrCode withScale:2*[[UIScreen mainScreen] scale]];

    // And push the image on to the screen
    self.qrImageView.image = qrCodeImg;

    // Re-enable the UI
    [self setUIElementsAsEnabled:YES];
}

Sunday, December 21, 2014

SecItemAdd Example


Storing in Keychain:
===============
NSData *secret = [@"top secret" dataWithEncoding: NSUTF9StringEncoding];
NSDictionary *query = @{
    (id)kSecClass : (id)kSecClassGenericPassword,
    (id)kSecAttrService : @"myservice",
    (id)kSecAttrAccount : @"account name here",
    (id)kSecValueData : secret
};

OSStatus status = SecItemAdd((CFDictionaryRef)query, NULL);



Retrieving from Keychain:
====================
NSDictionary *query = @{
    (id)kSecClass : (id)kSecClassGenericPassword,
    (id)kSecAttrService : @"myservice",
    (id)kSecAttrAccount : @"account name here",
    (id)kSecReturnData : @YES
};

NSData *data = NULL;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef*)&data);


KeychainItemWrapper Example

Add KeychainItemWrapper.h/.m from Apple

https://developer.apple.com/library/ios/samplecode/GenericKeychain/Introduction/Intro.html

KeychainItemWrapper* keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"KeychainTest" accessGroup:nil];
[keychain setObject:kSecAttrAccessibleWhenUnlocked forKey:kSecAttrAccessible];

NSLog(@"%@, %@", [keychain objectForKey:kSecAttrAccount], [keychain objectForKey:kSecValueData]);

[keychain setObject:@"example@email.com" forKey:kSecAttrAccount];
[keychain setObject:@"MySuperSecretPassword" forKey:kSecValueData];

[keychain release];
keychain = nil;

Tuesday, December 16, 2014

Hello World in node.js


var http = require('http');

var server = http.createServer(function(req, res) {
  res.writeHead(200);
  res.end('Hello Http');
});
server.listen(8080);

node.js plist

/*------------------------------
1. npm install plist
2. sudo npm install express
3. node node.js
--------------------------------*/

var plist = require('plist'),
    express = require('express')

var host = "127.0.0.1"
var port = 8080

var app = express()

app.get("/", function(request, response) {
        response.send(plist.build(
            {
                'Greeting': "Hello, World",
                'Price': 4.20,
                'FeatureXIsLaunched': true,
                'Status': 1
            }
        ).toString())
})

app.listen(port, host)


Monday, December 15, 2014

Fetching from Multiple Entities in CoreData:


@interface Employee : NSManagedObject

@property (nonatomic, retain) NSString * dept;
@property (nonatomic, retain) NSString * email;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Department *deptEmp;

@end


@interface Department : NSManagedObject

@property (nonatomic, retain) NSString * location;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Employee *deptEmp1;

@end

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


NSMutableString *queryString = [NSMutableString stringWithFormat:@"deptEmp1.name == %@ AND deptEmp1.location == %@", @"Apple", @"Cupertino"];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:self.managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"Department",nil]];
[request setIncludesSubentities:YES];

NSArray* returnArray = [self.managedObjectContext executeFetchRequest:request error:&error];
if([returnArray count] > 0) {

   Employee* emp = [returnArray objectAtIndex:0];
   NSLog(@"%@ %@ %@", emp.name, emp.dept, emp.deptEmp.location);
}


Sunday, December 14, 2014

Core Data Migration:


1. Create a new version of the core data.
2. Add/Update the changes in the new core data model.
3. Set the new core data model as active in xcode.
4. Add the following options dictionary to the Persistance store in AppDelegate.

  NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                           [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                           [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,  nil];

Friday, December 12, 2014

Cancel UILocalNotification:

NSString *myIDToCancel = @"some_id_to_cancel";
UILocalNotification *notificationToCancel=nil;
for(notificationToCancel in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
  if([[notificationToCancel.userInfo objectForKey:@"ID"] isEqualToString:myIDToCancel]) {
     break;
  }
}
[[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];

UILocalNotification in Background

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    __block UIBackgroundTaskIdentifier bgTask ;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    pollingTimer2 = [NSTimer scheduledTimerWithTimeInterval:4.0f target:self  selector:@selector(process)  userInfo:nil repeats:YES];
}
-(void) process
{
   [self didLocalNotification];

}

-(void)didLocalNotification
{

    [[UIApplication sharedApplication]cancelAllLocalNotifications];
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    if (localNotification == nil)
    {
        return;
    }

    NSLog(@"calling didLocalNotification");
    localNotification.applicationIconBadgeNumber =0;
    localNotification.alertBody =@"Message!";
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

UILocalNotification Example

UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSInterval interval;
switch( freqFlag ) {     // Where freqFlag is NSHourCalendarUnit for example
    case NSHourCalendarUnit:
        interval = 60 * 60;  // One hour in seconds
        break;
    case NSDayCalendarUnit:
        interval = 24 * 60 * 60; // One day in seconds
        break;
}
if( every == 1 ) {
    locNot.fireDate = [NSDate dateWithTimeInterval: interval fromDate: now];
    locNot.repeatInterval = freqFlag;
    [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
} else {
    for( int i = 1; i <= repeatCountDesired; ++i ) {
        locNot.fireDate = [NSDate dateWithTimeInterval: interval*i fromDate: now];
        [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
    }
}
[locNot release];

Tuesday, December 9, 2014

Binary Search

 NSArray  *arr = @[@1, @2, @5, @10];

  NSLog(@"arr : %@",arr);
 
  int result = [self searchIndexOfNumber: 5];
  if(result == -1) {
    NSLog(@"Number not found");
  } else {
    NSLog(@"Number found at index : %d", result);
  }


----------------------------------------

-(int)searchIndexOfNumber: (int)number{
  int result = -1;
 
  int lower = 0;
  int upper = (int)[arr count]-1;
 
  while (lower <= upper) {
    int mid = (lower + upper) / 2;
   
    if([arr[mid] integerValue] < number) {
     
      lower = mid + 1;
     
    } else if([arr[mid] integerValue] == number){
     
      result = mid;
      break;
     
    } else {
   
      upper = mid - 1;
    }
   
  }

  return result;
}

Friday, December 5, 2014

EKEventKit Example


To add an event:
================

EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = @"Event Title";
        event.startDate = [NSDate date]; //today
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour meeting
        [event setCalendar:[store defaultCalendarForNewEvents]];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
        NSString *savedEventId = event.eventIdentifier;  //this is so you can access this event later
    }];
  



To remove an event:
==================

 EKEventStore* store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent* eventToRemove = [store eventWithIdentifier:savedEventId];
        if (eventToRemove) {
            NSError* error = nil;
            [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
        }
    }];
  
  
----------------------------------------------


Event With Alarm Example:
=========================

EKEvent *event = [EKEvent eventWithEventStore: eventStore];
event.calendar = eventStore.defaultCalendarForNewEvents;
event.title = @"Some title";
event.allDay = YES;
event.startDate = self.date;
event.endDate = self.date;


EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:0];
event.alarms = @[alarm];

NSError *err = nil;
BOOL saved = [store saveEvent:event span:EKSpanThisEvent error:&err];
if(!saved && err){
    NSLog("Error : %@", [err localizedDescription];
} else {
   int eventId = event.eventIdentifier;
}




Thursday, December 4, 2014

Location Manager Changes in iOS 8.0



Add these in info.plist
---------------------------
NSLocationWhenInUseUsageDescription

NSLocationAlwaysUsageDescription


-(void)initLocationManager {
    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setDistanceFilter:100];
  
    if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
        //[self.locationManager requestWhenInUseAuthorization]; // Add This Line
    }
  
  
    if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
      [self.locationManager requestAlwaysAuthorization]; // Add This Line
    }
  
    [self.locationManager startUpdatingLocation];

}


#pragma mark - LocationManager Delegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
  
    NSLog(@"locationManager didUpdateLocations");
 
    [locationManager stopUpdatingLocation];
  
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
  
    [geoCoder reverseGeocodeLocation:[locations objectAtIndex:0] completionHandler:^(NSArray *placemarks, NSError *error) {
      
        CLPlacemark *placemark    = [placemarks objectAtIndex:0];
        NSString* countryName    = placemark.country;
        NSLog(@"Country Name: %@",countryName);
      
        self.countryNameString    = countryName;
    
    
        NSString *countryCode    = placemark.ISOcountryCode;

        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: countryName, @"countryName",
                              countryCode, @"countryCode", nil];
    
    
        if(self.geoLocationDelegate && [self.geoLocationDelegate respondsToSelector:@selector(receivedGeoLocationData:)]) {
          [self.geoLocationDelegate receivedGeoLocationData:dict];
        }
    
    
    }];
  
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    NSLog(@"Location Manager did fail : %@", [error localizedDescription]);
}

Country Code and Country Name from NSLocale

NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

NSString *country = [usLocale displayNameForKey:NSLocaleCountryCode value:countryCode];

Friday, November 28, 2014

Check Twitter Service availability on iOS Device



Add Social and Accounts framework:

 if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
   
   
    ACAccountStore *store = [[ACAccountStore alloc] init];
    ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    [store requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error) {
     
      if(error != nil) {
       
        NSLog(@"Twitter Error : %@", [error description]);
       
      } else {
       
        if(granted) {
         
          NSLog(@"Twitter permission granted");
         
        } else {
          NSLog(@"Twitter permission not granted");
        }
       
      }
     
    }];
   
  }
 

TouchID authentication in iOS


#import <LocalAuthentication/LocalAuthentication.h>


- (IBAction)authenicateButtonTapped:(id)sender {
 
  LAContext *context = [[LAContext alloc] init];
 
  NSError *error = nil;
 
  if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
   
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
            localizedReason:@"Are you the device owner?"
                      reply:^(BOOL success, NSError *error) {
                       
                       
                 
              dispatch_async(dispatch_get_main_queue(), ^{
                    // write all your code here
                 
                 
                  if (error) {
                   
                    if(error.code == kLAErrorUserFallback) {
                      [self passcodeFallback];
                    } else if(error.code == kLAErrorUserCancel) {
                      [self cancelLogin];
                    }
                   
                   
                    return;
                   
                  } else {
                 
                      if (success) {
                       
                        [self showAlertWithTitle:@"Success" andMessage:@"You are the device owner!"];

                       
                      } else {
                       
                        [self showAlertWithTitle:@"Error" andMessage:@"You are not the device owner."];

                      }
                  }
               
            });
                       
       }];

  } else {

   
    [self reportError];

   
  }
}


-(void)passcodeFallback {
  [self showAlertWithTitle:@"Error" andMessage:@"Show UI Screen to retrieve passcode from keychain"];

}

-(void)cancelLogin {
  [self showAlertWithTitle:@"Error" andMessage:@"Login Cancelled"];

}

-(void)reportError {
  [self showAlertWithTitle:@"Error" andMessage:@"Your deivice can't be authenticated"];
}


-(void)showAlertWithTitle:(NSString *)aTitle andMessage:(NSString *)aMsg {
 
 
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle
                                                  message:aMsg
                                                 delegate:nil
                                        cancelButtonTitle:@"Ok"
                                        otherButtonTitles:nil];
  [alert show];
 
}

Thursday, November 27, 2014

UIDocumentInteractionController Example


- (void)onOpenWith:(UIButton *)theButton path:(NSString *)path
{  
    NSURL *URL = [NSURL fileURLWithPath:path];
  
    if (URL) {
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
      
        self.documentInteractionController.delegate = self;
      
        //self.documentInteractionController.name = @"Title";
        //self.documentInteractionController.UTI = @"com.adobe.pdf"; @"net.whatsapp.image";
      
        //Preview PDF
        //[self.documentInteractionController presentPreviewAnimated:YES];
              
        //Open In iBooks     
       //presentOpenInMenuFromRect
       //presentOptionsMenuFromRect
        [self.documentInteractionController presentOpenInMenuFromRect:CGRectZero
                                              inView:aView
                                            animated:YES];
    }
}


#pragma mark - UIDocumentInteractionControllerDelegate

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return self.view.frame;
}

MPMoviePlayerViewController in Potrait and Landscape mode




- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)windowx
{
    if ([[self.window.rootViewController presentedViewController] isKindOfClass:[MPMoviePlayerViewController class]] ||
    [[self.window.rootViewController presentedViewController] isKindOfClass:NSClassFromString(@"MPInlineVideoFullscreenViewController")])
    {
        if ([self.window.rootViewController presentedViewController].isBeingDismissed)
        {
            return UIInterfaceOrientationMaskPortrait;
        }
        else
        {
            return UIInterfaceOrientationMaskAllButUpsideDown;
        }
    }
    else
    {
        return UIInterfaceOrientationMaskPortrait;
    }
}

Wednesday, November 26, 2014

iCloud Backup

Overview

iCloud includes Backup, which automatically backs up a user’s iOS device daily over Wi-Fi. Everything in your app’s home directory is backed up, with the exception of the application bundle itself, the caches directory, and temp directory. Purchased music, apps, books, the Camera Roll, device settings, home screen and app organization, messages, and ringtones are backed up as well. Because backups are done wirelessly and stored in iCloud for each user, it’s best to minimize the amount of data that’s stored for your app. Large files will lengthen the time it takes to perform a backup and consume more of a user’s available iCloud storage.

Storing Your App’s Data Efficiently

To ensure that backups are as efficient as possible, store your app’s data according to the following guidelines:
  1. Only documents and other data that is user-generated, or that cannot otherwise be recreated by your application, should be stored in the /Documents directory and will be automatically backed up by iCloud.
  2. Data that can be downloaded again or regenerated should be stored in the /Library/Caches directory. Examples of files you should put in the Caches directory include database cache files and downloadable content, such as that used by magazine, newspaper, and map applications.
  3. Data that is used only temporarily should be stored in the /tmp directory. Although these files are not backed up to iCloud, remember to delete those files when you are done with them so that they do not continue to consume space on the user’s device.
  4. Use the "do not back up" attribute for specifying files that should remain on device, even in low storage situations. Use this attribute with data that can be recreated but needs to persist even in low storage situations for proper functioning of your app or because customers expect it to be available during offline use. This attribute works on marked files regardless of what directory they are in, including the Documents directory. These files will not be purged and will not be included in the user's iCloud or iTunes backup. Because these files do use on-device storage space, your app is responsible for monitoring and purging these files periodically.

Excluding a File from Backup

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];

    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}




Thursday, November 20, 2014

Speedup MacOS:

Delete Cache files:
~/Library/Caches

Delete Log Files:
~/Library/Logs
 

Wednesday, November 19, 2014

Reverse GeoCoding in iOS




#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface NearByViewController : UIViewController <CLLocationManagerDelegate>


@property (weak, nonatomic) IBOutlet UILabel *latLbl;
@property (weak, nonatomic) IBOutlet UILabel *lngLbl;
@property (weak, nonatomic) IBOutlet UILabel *addressLbl;


@end




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



#import "NearByViewController.h"


@interface NearByViewController () {
  CLLocationManager *locationManager;
}

@end

@implementation NearByViewController


-(void)initializeLocationManager {
  locationManager = [[CLLocationManager alloc] init];
  [locationManager setDelegate:self];
  [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
  [locationManager setDistanceFilter:100];
  [locationManager startUpdatingLocation];
 
  if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
    [locationManager requestWhenInUseAuthorization]; // Add This Line
  }
 
  NSLog(@"Location Manager is initialised");
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
  [self initializeLocationManager];
}





#pragma mark - LocationManager Delegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
 
  /*
   if(currentLocation.latitude == 0.0 && currentLocation.longitude == 0.0) {
   currentLocation = manager.location.coordinate;
   NSLog(@"Latitude : %.2f, Longitude : %.2f", currentLocation.latitude, currentLocation.longitude);
  
   }
   */
 
 
  NSLog(@"Location manager didupdate in NearByViewController");
 
  CLLocation *currentLocation =    manager.location;
 
//  NSLog(@"Current Location 11 : %f , %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
 
 
  self.latLbl.text = [NSString stringWithFormat:@"%0.3f", currentLocation.coordinate.latitude];
  self.lngLbl.text = [NSString stringWithFormat:@"%0.3f", currentLocation.coordinate.longitude];
 
 
//  currentLocation = [locations lastObject];
//  NSLog(@"Current Location 22 : %f , %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);

 
 
 
  [locationManager stopUpdatingLocation];
 
  CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
  [geoCoder reverseGeocodeLocation:[locations objectAtIndex:0] completionHandler:^(NSArray *placemarks, NSError *error) {
   
   
   
    CLPlacemark *placemark = [placemarks objectAtIndex:0];
   
    /*
    isoCountryCode.text      = placemark.ISOcountryCode;
    country.text          = placemark.country;
    postalCode.text          = placemark.postalCode;
    adminArea.text          = placemark.administrativeArea;
    subAdminArea.text      = placemark.subAdministrativeArea;
    locality.text          = placemark.locality;
    subLocality.text      = placemark.subLocality;
    thoroughfare.text      = placemark.thoroughfare;
    subThoroughfare.text  = placemark.subThoroughfare;
    */
   
    NSString *address = [NSString stringWithFormat:@"%@\n%@ %@\n%@\n%@",
                         placemark.thoroughfare,
                         placemark.postalCode, placemark.locality,
                         placemark.administrativeArea,
                         placemark.country];
   
    NSLog(@"Address : %@", address);
   
    self.addressLbl.text = address;
   
  }];
 
   
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
  NSLog(@"Location Manager did fail : %@", [error localizedDescription]);
}


#pragma mark -


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end






Monday, November 17, 2014

Controlling Line Spacing using AttributedString

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 17;
textView.attributedText = [[NSAttributedString alloc] 
    initWithString:@"Predefined Text" 
    attributes:@{NSParagraphStyleAttributeName : style}];
textView.text = @"Your text"
 
 
 

Monday, November 10, 2014

Formatting html at runtime:


1. Add custom font files in Proj.plist file
2. Insert the css styles at runtime.

NSString* htmlString = [NSString stringWithFormat:@"<html><head><style type=\"text/css\">"
                             @"@font-face {"
                             @"font-family: 'ITCAvantGardeStd-Bk';"
                             @"src: url('ITCAvantGardeStd-Bk.otf')  format('truetype')"
                             @"}"
                             @"@font-face {"
                             @"font-family: 'ITCAvantGardeStd-Bold';"
                             @"src: url('ITCAvantGardeStd-Bold.otf')  format('truetype')"
                             @"}"
                             @"body {"
                                @"font-family: ITCAvantGardeStd-Bk;"
                                @"font-size: 9pt;"
                                @"color: #969B9D"
                                @"}"
                             @"p{ font-family: 'ITCAvantGardeStd-Bk'; }"
                             @"strong {font-family: 'ITCAvantGardeStd-Bold';color:#5F656A;}"
                             @"</style></head><body>%@</body></html>",[self.contentDict1 objectForKey:@"bodyHTML"]];

Wednesday, November 5, 2014

Steps for fixing Macbook Pro issues:


Macbook HardDisk Repair/Format:
-----------------------------------------------
a) Create the bootable USB drive with Yosemite

(i) Format the USB drive with GUID Partition
(ii) Download Yosemite from AppStore and quit the installer.
(iii) Type the below command on MacOS Terminal

sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app --nointeraction

b) Restart the Macbook and boot from USB Drive    

    (i) Hold down the Option key while rebooting
    (ii) Click on the USB drive icon to boot

    or ( Boot using Command + S , and then select USB as “Startup Disk” )


c) Format / Repair Disk the main HDD




Battery Repair ( Resetting the System Management Controller - SMC )
—————————----------------------------------------------------------------—
a) Shutdown the Macbook
b) Unplug the Power Cable
c) Remove the battery from Macbook , wait for 1 minute
d) Tap and hold the power on button for 5 seconds
e) Connect the battery back to Macbook
f) Reconnect the Power Cable and restart





Fix for trouble logging into MacOS:
----------------------------------------------
Steps:
(a) Hold Command + s and press Power On key
(b) #root: /sbin/mount -uw /
(c) #root: chmod 775 /
(d) #root: logout
(e) Hold Command + v while restarting





How To Reset PRAM:
=================

Step 1: Turn off your Mac. No need to remove the battery or detaching the power chord.

Step 2: Turn on your Mac and hold down the Command+Option+P+R keys, all at the same time.

Step 3: Hold down all four keys until you hear the startup sound twice.

The startup sound for the second time means you’ve reset the PRAM.







How To Reset SMC:
================

(a) For MacBooks With Removable Battery
---------------------------------------------------------
Step 1: Shut down the Mac, remove the back plate and disconnect the battery.

Step 2: Press and hold the power button for five seconds before releasing.

Step 3: Connect the battery and turn the Mac back on.



(b) For MacBooks Without Removable Battery
-------------------------------------------------------------
Step 1: Shut down the Mac and make sure it is plugged in to a power source.

Step 2: When the Mac is off, press and hold Shift+Control+Option keys as well as the Power button.

Step 3: Release all four keys at the same time. The Mac should not power on during this time.

Step 4: Press the power button to turn the Mac back on.




MacOS HardDisk Repair/Format



Steps:
--------

a) Create the bootable USB drive with Yosemite

(i) Format the USB drive with GUID Partition
(ii) Download Yosemite from AppStore and quit the installer.
(iii) Type the below command on MacOS Terminal

sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app --nointeraction

b) Restart the Macbook and boot from USB Drive

c) Format / Repair Disk the main HDD

Resetting the System Management Controller (SMC)


1. Shut down the computer.
2. Disconnect the MagSafe power adapter from the computer, if it's connected.
3. Remove the battery.
4. Press and hold the power button for 5 seconds.
5. Release the power button.
6. Reconnect the battery and MagSafe power adapter.
7. Press the power button to turn on the computer.



Mac OS Booting Problem


Mac OS Booting Problem:
======================

Try the following commands to fix the booting problem in Mac OS X


Command + R       (Recovery Mode)

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

Command + Shift + V

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

Command + Option + P + R

hey!, try this method then 1.Shut down the computer. 2.Locate the following keys on the keyboard: Command, Option, P, and R. You will need to hold these keys down simultaneously in step 4. 3.Turn on the computer. 4.Press and hold the Command-Option-P-R keys. You must press this key combination before the gray screen appears. 5.Hold the keys down until the computer restarts and you hear the startup sound for the second time. 6.Release the keys and it should boot:)

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

Hey I repair macbook's, i get this problems some times, to fix this you just got to hold command + s then you get a black screen just wait until you see: root.
Then type /sbin/mount -uw /
Then type chmod 775 /
Then type logout and then it will boot after that, shut down your mac and then hold command + v and let it do it's work!

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

UIAlertController Example


UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                               message:@"\n\n\n\n\n\n\n\n\n\n\n"             preferredStyle:UIAlertControllerStyleActionSheet];

__weak typeof(self) weakSelf = self;
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    [weakSelf pickActionSheetFinishAction];
}];

[alertController addAction:cancelAction];
[alertController.view addSubview:self.topicPickView];
[self presentViewController:alertController animated:YES completion:nil];


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


UIAlertController * searchActionSheet=[UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

[ searchActionSheet.view setBounds:CGRectMake(7, 180, self.view.frame.size.width, 470)];

//yourView represent the view that contains UIPickerView and toolbar
[searchActionSheet.view addSubview:self.yourView];
[self presentViewController:searchActionSheet animated:YES completion:nil];

Friday, October 24, 2014

Tuesday, October 21, 2014

URLEncoding Example


NSString *post = [NSString stringWithFormat:@"searchInput=%@&searchType=%@",[self urlEncodeValue:searchText],[self urlEncodeValue:searchBy]];
 

- (NSString *)urlEncodeValue:(NSString *)str
{
 NSString *result = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8));
 return result ;
}

Sunday, October 19, 2014

iBeacon Example



1. Two iPhone4s are used to simulate the iBeacons
2. uuidgen is used using the Terminal for generating the UUIDString


Broadcast:
==========
#import <CoreLocation/CoreLocation.h>
#import <CoreBluetooth/CoreBluetooth.h>


@interface ViewController : UIViewController<CBPeripheralManagerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (strong, nonatomic) CLBeaconRegion *myBeaconRegion;
@property (strong, nonatomic) NSDictionary *myBeaconData;
@property (strong, nonatomic) CBPeripheralManager *peripheralManager;

@end

-------------------------------------------------------------------------

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
 
    // Create a NSUUID object
    NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"A77A1B68-49A7-4DBF-914C-760D07FBB87B"];
 
    // Initialize the Beacon Region
    self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
                                                                  major:1
                                                                  minor:1
                                                             identifier:@"com.appcoda.testregion"];
}


- (IBAction)buttonClicked:(id)sender {
 
    // Get the beacon data to advertise
    self.myBeaconData = [self.myBeaconRegion peripheralDataWithMeasuredPower:nil];
 
    // Start the peripheral manager
    self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self
                                                                     queue:nil
                                                                   options:nil];
}



-(void)peripheralManagerDidUpdateState:(CBPeripheralManager*)peripheral
{
    if (peripheral.state == CBPeripheralManagerStatePoweredOn)
    {
        // Bluetooth is on
     
        // Update our status label
        self.statusLabel.text = @"Broadcasting...";
     
        // Start broadcasting
        [self.peripheralManager startAdvertising:self.myBeaconData];
    }
    else if (peripheral.state == CBPeripheralManagerStatePoweredOff)
    {
        // Update our status label
        self.statusLabel.text = @"Stopped";

        // Bluetooth isn't on. Stop broadcasting
        [self.peripheralManager stopAdvertising];
    }
    else if (peripheral.state == CBPeripheralManagerStateUnsupported)
    {
        self.statusLabel.text = @"Unsupported";
    }
}





Receiver's:
===========

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>

@property (strong, nonatomic) CLBeaconRegion *myBeaconRegion;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;

@end



-------------------------------------------------------------------------




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
 
    // Initialize location manager and set ourselves as the delegate
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
 
    // Create a NSUUID with the same UUID as the broadcasting beacon
    NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"A77A1B68-49A7-4DBF-914C-760D07FBB87B"];
 
    // Setup a new region with that UUID and same identifier as the broadcasting beacon
    self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
                                                             identifier:@"com.appcoda.testregion"];
 
    // Tell location manager to start monitoring for the beacon region
    [self.locationManager startMonitoringForRegion:self.myBeaconRegion];
}




- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion*)region
{
    [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
   
   
    //-------------- Create LocalNotification to alert User ------------------
   
  UILocalNotification *notificaiton = [[UILocalNotification alloc] init];
  notificaiton.alertBody = @"Welcome User";
  notificaiton.soundName = @"Default";
  [[UIApplication sharedApplication] presentLocalNotificationNow:notificaiton];
   
}


-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion*)region
{
    [self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
    self.beaconFoundLabel.text = @"No";
   
   
//-------------- Create LocalNotification to alert User ------------------

  UILocalNotification *notificaiton = [[UILocalNotification alloc] init];
  notificaiton.alertBody = @"GoodBye";
  notificaiton.soundName = @"Default";
  [[UIApplication sharedApplication] presentLocalNotificationNow:notificaiton];

}



-(NSString *)nameForProximity:(CLProximity)proximity {
switch(proximity) {

case CLProximityUnknown:
return @"Unknown";
break;

case CLProximityImmediate:
return @"Immediate";
break;

case CLProximityNear:
return @"Near";
break;

case CLProximityFar:
return @"Far";
break;

}
}



-(void)locationManager:(CLLocationManager*)manager
       didRangeBeacons:(NSArray*)beacons
              inRegion:(CLBeaconRegion*)region
{
 
   if(beacons.count) {

// Beacon found!
self.statusLabel.text = @"Beacon found!";


CLBeacon *foundBeacon = [beacons firstObject];
   NSLog(@"Message : %@", [self nameForProximity: foundBeacon.proximity);
 
// You can retrieve the beacon data from its properties
//NSString *uuid = foundBeacon.proximityUUID.UUIDString;
//NSString *major = [NSString stringWithFormat:@"%@", foundBeacon.major];
//NSString *minor = [NSString stringWithFormat:@"%@", foundBeacon.minor];

    } else {
   
    NSLog(@"No beacons found");
   
    }
}





CoreAnimation Basics


(a) Shake password field if wrong password is entered:


CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.keyPath = @"position.x";
animation.values = @[ @0, @10, @-10, @10, @0 ];
animation.keyTimes = @[ @0, @(1 / 6.0), @(3 / 6.0), @(5 / 6.0), @1 ];
animation.duration = 0.4;

animation.additive = YES;

[form.layer addAnimation:animation forKey:@"shake"];


---------------------------------------------------------------------


(b) Animation Along a Path:


CGRect boundingRect = CGRectMake(-150, -150, 300, 300);

CAKeyframeAnimation *orbit = [CAKeyframeAnimation animation];
orbit.keyPath = @"position";
orbit.path = CFAutorelease(CGPathCreateWithEllipseInRect(boundingRect, NULL));
orbit.duration = 4;
orbit.additive = YES;
orbit.repeatCount = HUGE_VALF;
orbit.calculationMode = kCAAnimationPaced;
orbit.rotationMode = kCAAnimationRotateAuto; //nil

[satellite.layer addAnimation:orbit forKey:@"orbit"];


----------------------------------------------------------------------


(c) Translation:


CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"position.x";
animation.fromValue = @50;
animation.toValue = @150;
animation.duration = 1;

animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; //kCAMediaTimingFunctionEaseInEaseOut

[rectangle.layer addAnimation:animation forKey:@"basic"];

rectangle.layer.position = CGPointMake(150, 0);



----------------------------------------------------------------------