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);



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









NSURLSession in iOS 7.0


NSURLSession:
=============

 NSURL *URL = [NSURL URLWithString:@"http://example.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];

 [NSURLConnection sendAsynchronousRequest:request
                                    queue:[NSOperationQueue mainQueue]
                        completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
     // ...
 }];

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

Data tasks can be created with either an NSURL or NSURLRequest (the former being a shortcut for a standard GET request to that URL):


 NSURL *URL = [NSURL URLWithString:@"http://example.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];

 NSURLSession *session = [NSURLSession sharedSession];
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error) {
         // ...
     }];

 [task resume];

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

Upload tasks can also be created with a request and either an NSData object for a URL to a local file to upload:


 NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];
 NSData *data = ...;

 NSURLSession *session = [NSURLSession sharedSession];
 NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                            fromData:data
                                                   completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error) {
         // ...
     }];

 [uploadTask resume];


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

Download requests take a request as well, but differ in their completionHandler. Rather than being returned all at once upon completion, as data and upload tasks, download tasks have their data written to a local temp file. It’s the responsibility of the completion handler to move the file from its temporary location to a permanent location.


 NSURL *URL = [NSURL URLWithString:@"http://example.com/file.zip"];
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];

 NSURLSession *session = [NSURLSession sharedSession];
 NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request
                                                         completionHandler:
    ^(NSURL *location, NSURLResponse *response, NSError *error) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
        NSURL *documentURL = [documentsDirectoryURL URLByAppendingPathComponent:[response
suggestedFilename]];
        [[NSFileManager defaultManager] moveItemAtURL:location
                                                toURL:documentURL
                                                error:nil];
 }];

 [downloadTask resume];


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


NSURLSessionConfiguration:
==========================


NSString *imageUrl =
@"http://www.raywenderlich.com/images/store/iOS7_PDFonly_280@2x_authorTBA.png";

NSURLSessionConfiguration *sessionConfig =
  [NSURLSessionConfiguration defaultSessionConfiguration];
 
 
 
NSString *userPasswordString = [NSString stringWithFormat:@"%@:%@", user, password];
NSData * userPasswordData = [userPasswordString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential];
NSString *userAgentString = @"AppName/com.example.app (iPhone 5s; iOS 7.0.2; Scale/2.0)";


sessionConfig.HTTPAdditionalHeaders = @{@"Accept": @"application/json",
                                        @"Accept-Language": @"en",
                                        @"Authorization": authString,
                                        @"User-Agent": userAgentString};
                                                                              
sessionConfig.allowsCellularAccess = NO;
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
sessionConfig.HTTPMaximumConnectionsPerHost = 1;




NSURLSession *session =
  [NSURLSession sessionWithConfiguration:sessionConfig
                                delegate:self
                           delegateQueue:nil];
                          
                          


// 1
NSURLSessionDownloadTask *getImageTask =
[session downloadTaskWithURL:[NSURL URLWithString:imageUrl]

    completionHandler:^(NSURL *location,
                        NSURLResponse *response,
                        NSError *error) {
        // 2
        UIImage *downloadedImage =
          [UIImage imageWithData:
              [NSData dataWithContentsOfURL:location]];
      //3
      dispatch_async(dispatch_get_main_queue(), ^{
        // do stuff with image
        _imageWithBlock.image = downloadedImage;
      });
}];

// 4
[getImageTask resume];


Delegates:
-----------

-(void)URLSession:(NSURLSession *)session
     downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
  // use code above from completion handler
}



-(void)URLSession:(NSURLSession *)session
     downloadTask:(NSURLSessionDownloadTask *)downloadTask
     didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
  NSLog(@"%f / %f", (double)totalBytesWritten,
    (double)totalBytesExpectedToWrite);
}


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

REST API Call


//NSString *post = @"key1=val1&key2=val2";

NSString *post = [NSString stringWithFormat:@"key1=%@&key2=%@",[self urlEncodeValue:val1],[self urlEncodeValue:val2]];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];


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


[NSURLConnection sendAsynchronousRequest:request
                                    queue:[NSOperationQueue mainQueue]
                        completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    
    
     if(!error){
    
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if(httpResponse.statusCode == 200){
       
        } else {
            NSLog(@"Invalid Response : %d", (int)httpResponse.statusCode);           
        }
    
     } else {
         NSLog("@"Error : %@", error);
     }
    
 }];


 

Friday, October 17, 2014

What is key-value coding ?


The idea behind key-value coding is pretty simple: instead of directly getting and setting specific properties on an object, key-value coding involves passing in a "key" (usually a string) and getting or setting the property associated with that key.


For example:
// Set a property directly...
someObject.someProperty = someValue;

// ...or set the same property using key-value coding
[someObject setValue:someValue forKey:@"someProperty"];

Pass generation in PHP

<?php

    ...Some Code...

    header('Content-Type: application/vnd.apple.pkpass');
    header('Content-Length: ' . filesize($filename));
    readfile($filename);
?>

Thursday, October 16, 2014

Vector Algebra


static inline CGVector TCVectorMultiply(CGVector vector, CGFloat m);

static inline CGVector TCVectorMinus(CGPoint p1, CGPoint p2)
{
    return CGVectorMake(
        p1.x - p2.x,
        p1.y - p2.y
    );
}

static inline CGFloat TCVectorLength(CGVector vector)
{
    return sqrtf(vector.dx * vector.dx + vector.dy * vector.dy);
}

static inline CGVector TCVectorUnit(CGVector vector)
{
    CGFloat invLen = 1.0 / TCVectorLength(vector);
    return TCVectorMultiply(vector, invLen);
}

static inline CGVector TCVectorMultiply(CGVector vector, CGFloat m)
{
    return CGVectorMake(
        vector.dx * m,
        vector.dy * m
    );
}

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


static inline CGPoint CGPointMultiplyScalar( const CGPoint a, const CGFloat b )
{
  return CGPointMake(a.x * b, a.y * b);
}


static inline CGPoint CGPointAdd( const CGPoint a, const CGPoint b)
{
  return CGPointMake(a.x + b.x , a.y + b.y);
}


Friday, October 10, 2014

Functions inside Structure in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct point
{
    int x;
    int y;
    void (*print)(const struct point*);
};

void print_x(const struct point* p)
{
    printf("x=%d\n", p->x);
}

void print_y(const struct point* p)
{
    printf("y=%d\n", p->y);
}

int main(void)
{
    struct point p1 = { 2, 4, print_x };
    struct point p2 = { 7, 1, print_y };

    p1.print(&p1);
    p2.print(&p2);

    return 0;
}
 
 

Friday, October 3, 2014

Image Processing in ObjC



Combine two UIImages
-----------------------------
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 { 
    UIGraphicsBeginImageContext(image1.size); 
 
    // Draw image1 
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)]; 
 
    // Draw image2 
    [image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)]; 
 
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); 
 
    UIGraphicsEndImageContext(); 
 
    return resultingImage; 





Create a UIImage from a part of another UIImage:
------------------------------------------------------------
- (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect { 
    CGImageRef sourceImageRef = [image CGImage]; 
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); 
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; 
    CGImageRelease(newImageRef); 
    return newImage; 
}



Save UIImage to Photo Album:
--------------------------------------
UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), context); 
   
   
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { 
    NSString *message; 
    NSString *title; 
    if (!error) { 
        title = NSLocalizedString(@"SaveSuccessTitle", @""); 
        message = NSLocalizedString(@"SaveSuccessMessage", @""); 
    } else { 
        title = NSLocalizedString(@"SaveFailedTitle", @""); 
        message = [error description]; 
    } 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title 
                                                    message:message 
                                                   delegate:nil 
                                          cancelButtonTitle:NSLocalizedString(@"ButtonOK", @"") 
                                          otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
}



Waze API


search for address:         waze://?q=

center map to lat / lon:     waze://?ll=,
navigate to lat / lon:         waze://?ll=,&navigate=yes
set zoom (minimum is 6):     waze://?z=


- (void) navigateToLatitude:(double)latitude
                  longitude:(double)longitude
{
  if ([[UIApplication sharedApplication]
    canOpenURL:[NSURL URLWithString:@"waze://"]]) {

      // Waze is installed. Launch Waze and start navigation
      NSString *urlStr =
        [NSString stringWithFormat:@"waze://?ll=%f,%f&navigate=yes",
        latitude, longitude];

      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];

   } else {

      // Waze is not installed. Launch AppStore to install Waze app
      [[UIApplication sharedApplication] openURL:[NSURL
        URLWithString:@"http://itunes.apple.com/us/app/id323229106"]];
   }
}


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

try
{
   String url = "waze://?q=Hawaii";
    Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
   startActivity( intent );
}
catch ( ActivityNotFoundException ex  )
{
  Intent intent =
    new Intent( Intent.ACTION_VIEW, Uri.parse( "market://details?id=com.waze" ) );
  startActivity(intent);
}

Thursday, October 2, 2014

Adding Rounded Corners to UIView


CGRect bounds = (UIView*).bounds;
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                               byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                     cornerRadii:CGSizeMake(10.0, 10.0)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = maskPath.CGPath;

(UIView*).layer.mask = maskLayer;

Reversing Array in ObjC



@implementation NSArray (Reverse)

- (NSArray *)reversedArray {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
    NSEnumerator *enumerator = [self reverseObjectEnumerator];
    for (id element in enumerator) {
        [array addObject:element];
    }
    return array;
}

@end

@implementation NSMutableArray (Reverse)

- (void)reverse {
    if ([self count] == 0)
        return;
    NSUInteger i = 0;
    NSUInteger j = [self count] - 1;
    while (i < j) {
        [self exchangeObjectAtIndex:i
                  withObjectAtIndex:j];

        i++;
        j--;
    }
}

@end


Running Tasks,Localnotifications in Background:



- (void)applicationDidEnterBackground:(UIApplication *)application {
 
  if ([[UIDevice currentDevice] isMultitaskingSupported]) {
   
    UIApplication *application = [UIApplication sharedApplication];
   
    __block UIBackgroundTaskIdentifier background_task;
    background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
     
      NSLog(@"ExpirationHandler about to expire...");
//      [application endBackgroundTask: background_task];
//      background_task = UIBackgroundTaskInvalid;
    }];
   
   
    NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue addOperationWithBlock:^{
   
      // Perform long-running tasks without blocking main thread
     
      while(TRUE)
      {
        //backgroundTimeRemaining time does not go down.
       
        //NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
       
        UIDevice *device              = [UIDevice currentDevice];
        NSLog(@"Battey Level : %f", (device.batteryLevel));
       
        if(device.batteryLevel == 0.20f) {
          NSLog(@"Should show alert view.....for local notifications");
         
          int currentBatteryLevel      = (int)(device.batteryLevel * 100);

         
          NSDate *now = [NSDate date];
          NSCalendar *calendar = [NSCalendar currentCalendar];
          NSDateComponents *components = [[NSDateComponents alloc] init];
          [components setSecond:5];
          NSDate *dateTime = [calendar dateByAddingComponents:components
                                                              toDate:now
                                                             options:0];
         
         
          UILocalNotification *localNotification = [[UILocalNotification alloc] init];
          localNotification.fireDate = dateTime;
          localNotification.alertBody = [NSString stringWithFormat:@"Battery Level : %d percent", currentBatteryLevel];
          localNotification.soundName = UILocalNotificationDefaultSoundName;
          //localNotification.applicationIconBadgeNumber = 1;
          [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
         
         
            [application endBackgroundTask: background_task];
            background_task = UIBackgroundTaskInvalid;
        }
       
        [[NSNotificationCenter defaultCenter] postNotificationName:@"UIDeviceBatteryLevelDidChangeNotification" object:self userInfo:nil];
       
        [NSThread sleepForTimeInterval:10]; //wait for 1 sec

      }
     
    }];
   
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           
      // Wait until the pending operations finish
      [operationQueue waitUntilAllOperationsAreFinished];

     
      NSLog(@"ExpirationHandler is called");

    });
  }
}

UUID in iOS



// Get UUID value
NSUUID  *uuid = [NSUUID UUID];

// Convert UUID to string and output result
NSLog(@"UUID: %@", [uuid UUIDString]);


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


CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef identifier = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);

NSString *uuidString = CFBridgingRelease(identifier);


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

Parse Linker Errors


1.Remove -ObjC and -all_load in Other Linker Flags
2.Add -force_load to load only CocoaLibSpotify.

Example :
-force_load $(SRCROOT)/GoogleAdmob/fileName.a





NSURLAuthenticationChallenge




#pragma mark - NSURLConnection delegate for Handling HTTPS
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace {
  NSLog(@"Authentication String : %@", NSURLAuthenticationMethodServerTrust);
 
  NSLog(@"protectionSpace.authenticationMethod : %@", protectionSpace.authenticationMethod);
 
  //return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
 
  return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
 
  NSLog(@"challenge.protectionSpace.authenticationMethod : %@", challenge.protectionSpace.authenticationMethod);
 
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    NSLog(@"************ CERTIFICATE DOWNLOADED ***************");
  }
  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
 
}

Creating SHA1 for Android Apps



Susantas-MacBook-Pro-2:Desktop susantabehera$ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

Enter keystore password:
Alias name: androiddebugkey
Creation date: Mar 21, 2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 4f695d8f
Valid from: Wed Mar 21 12:48:15 MYT 2012 until: Fri Mar 14 12:48:15 MYT 2042
Certificate fingerprints:
     MD5:  22:CF:6E:A9:BD:23:73:61:0E:25:A9:2E:3E:9D:C3:DB
     SHA1: 8D:87:F2:55:CE:E3:70:28:91:2C:86:BE:6C:F2:2C:1E:50:F5:22:D0
     Signature algorithm name: SHA1withRSA
     Version: 3
    
Susantas-MacBook-Pro-2:Desktop susantabehera$


Vibrate UIView



#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)


+ (void)vibrateView:(UIView*)view
{
    CABasicAnimation *shiverAnimationR;
    shiverAnimationR = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    shiverAnimationR.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(1)];
    //shiverAnimationR.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(-10)];
    shiverAnimationR.duration = 0.1;
    shiverAnimationR.repeatCount = 1000000.0; // Use A high Value
    shiverAnimationR.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [view.layer addAnimation: shiverAnimationR forKey:@"shiverAnimationR"];


    CABasicAnimation * shiverAnimationL;
    shiverAnimationL = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //shiverAnimationL 2.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(10)];
    shiverAnimationL.toValue = [NSNumber numberWithFloat:DEGREES_TO_RADIANS(-1)];
    shiverAnimationL.duration = 0.1;
    shiverAnimationL.repeatCount = 1000000.0;
    shiverAnimationL.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [view.layer addAnimation: shiverAnimationL forKey:@"shiverAnimationL"];


}

Set UILabel Vertically



NSString *string = @"Lorem Ipsum";
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];

UILabel *label = [[UILabel alloc] init];
label.font = font;
label.text = string;

CGSize size = [string sizeWithAttributes:@{NSFontAttributeName:font}];
label.frame = CGRectMake(40, 40, size.width, size.height);
[label.layer setAnchorPoint:CGPointMake(0.0, 0.0)];
label.transform = CGAffineTransformMakeRotation((M_PI) / 2);


[self.view addSubview:label];

Convert NSDictionary to NSString



Sometime we need to convert the dictionary(received from server or database)
to the JSON string. We can use this simple function.


+ (NSString*) convertDictionaryToString:(NSMutableDictionary*) dict
{
    NSError* error;
    NSDictionary* tempDict = [dict copy]; // get Dictionary from mutable Dictionary
    //giving error as it takes dic, array,etc only. not custom object.
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:tempDict
                                                       options:NSJSONReadingMutableLeaves error:&error];
    NSString* nsJson=  [[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];
    return nsJson;

}

Convert Hex color code to UIColor



#define kBgColorCode    @"2c76c2"



[self.view setBackgroundColor:[Self colorWithHexString:kBgColorCode]];


+(UIColor*)colorWithHexString:(NSString*)hex
{
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
  
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor grayColor];
  
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
  
    if ([cString length] != 6) return  [UIColor grayColor];
  
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
  
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
  
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
  
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
  
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


iOS appStoreReceiptURL into Base64 Encoded String



// this returns an NSDictionary of the app's store receipt, status=0 for good, -1 for bad
- (NSDictionary *) getStoreReceipt:(BOOL)sandbox {

    NSArray *objects;
    NSArray *keys;
    NSDictionary *dictionary;

    BOOL gotreceipt = false;

    @try {

        NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];

        if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptUrl path]]) {

            NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];

            NSString *receiptString = [self base64forData:receiptData];

            if (receiptString != nil) {

                objects = [[NSArray alloc] initWithObjects:receiptString, nil];
                keys = [[NSArray alloc] initWithObjects:@"receipt-data", nil];
                dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

                NSString *postData = [self getJsonStringFromDictionary:dictionary];

                NSString *urlSting = @"https://buy.itunes.apple.com/verifyReceipt";
                if (sandbox) urlSting = @"https://sandbox.itunes.apple.com/verifyReceipt";

                dictionary = [self getJsonDictionaryWithPostFromUrlString:urlSting andDataString:postData];

                if ([dictionary objectForKey:@"status"] != nil) {

                    if ([[dictionary objectForKey:@"status"] intValue] == 0) {

                        gotreceipt = true;

                    }
                }

            }

        }

    } @catch (NSException * e) {
        gotreceipt = false;
    }

    if (!gotreceipt) {
        objects = [[NSArray alloc] initWithObjects:@"-1", nil];
        keys = [[NSArray alloc] initWithObjects:@"status", nil];
        dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
    }

    return dictionary;
}



- (NSDictionary *) getJsonDictionaryWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
    NSString *jsonString = [self getStringWithPostFromUrlString:urlString andDataString:dataString];
    NSLog(@"%@", jsonString); // see what the response looks like
    return [self getDictionaryFromJsonString:jsonString];
}


- (NSDictionary *) getDictionaryFromJsonString:(NSString *)jsonstring {
    NSError *jsonError;
    NSDictionary *dictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData:[jsonstring dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
    if (jsonError) {
       dictionary = [[NSDictionary alloc] init];
    }
    return dictionary;
}


- (NSString *) getStringWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
    NSString *s = @"";
    @try {
        NSData *postdata = [dataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postlength = [NSString stringWithFormat:@"%d", [postdata length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];
            [request setTimeoutInterval:60];
        [request setHTTPMethod:@"POST"];
        [request setValue:postlength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postdata];
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        if (data != nil) {
            s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
    }
    @catch (NSException *exception) {
        s = @"";
    }
    return s;
}


// from http://stackoverflow.com/questions/2197362/converting-nsdata-to-base64
- (NSString*)base64forData:(NSData*)theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}


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

Just heads up if you are getting a 21004 error, dont forget to send your application shared secret... like this NSString *password = @"your shared secret string"; objects = [[NSArray alloc] initWithObjects:receiptString, password, nil]; keys = [[NSArray alloc] initWithObjects:@"receipt-data", @"password", nil];

Add Done Button on Number Keypad



[self doneWithNumberPad];


-(void)doneWithNumberPad
{
    UIToolbar* doneToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    doneToolbar.barStyle = UIBarStyleBlackTranslucent;
    doneToolbar.items = [NSArray arrayWithObjects:
                         [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                         [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonAction)],
                         nil];
    [doneToolbar sizeToFit];
  
    self.textViewDescription.inputAccessoryView = doneToolbar;
 
  
}

-(void)doneButtonAction
{
    [self.textViewDescription resignFirstResponder];
}

Redirect NSLog to File



Step 1: Include following function in AppDelegate:


- (void)redirectNSLogToDocumentFolder
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
   
    NSString *documentsDirectory = [paths objectAtIndex:0];
   
    NSString *fileName =[NSString stringWithFormat:@"NSLogFile"];
   
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
   
    NSLog(@"Redirecting NSLog to file");
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
   
}


Step 2: Call this function at the start of function applicationDidFinishLaunchingWithOptions...


Thats it, Every NSLog() will now get redirected to this console.log file, which you can find in the documents directory.

Image Colouring in ObjC



+ (UIImage*)imageNamed:(NSString*)imgName withColor: (UIColor*)color {
  // load the image
  UIImage *img = [UIImage imageNamed:imgName];
 
  // begin a new image context, to draw our colored image onto
  UIGraphicsBeginImageContext(img.size);
 
  // get a reference to that context we created
  CGContextRef context = UIGraphicsGetCurrentContext();
 
  // set the fill color
  [color setFill];
 
  // translate/flip the graphics context (for transforming from CG* coords to UI* coords
  CGContextTranslateCTM(context, 0, img.size.height);
  CGContextScaleCTM(context, 1.0, -1.0);
 
  // set the blend mode to color burn, and the original image
  CGContextSetBlendMode(context, kCGBlendModeNormal);
  CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
  CGContextDrawImage(context, rect, img.CGImage);
 
  // set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
  CGContextClipToMask(context, rect, img.CGImage);
  CGContextAddRect(context, rect);
  CGContextDrawPath(context,kCGPathFill);
 
  // generate a new UIImage from the graphics context we drew onto
  UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
 
  //return the color-burned image
  return coloredImg;
}


Wednesday, September 24, 2014

Installing Maven and JDK on MacOS



Installing maven on Mac OS:
-------------------------------------

a) Copy the maven folder inside "/usr/local” folder , which will look like this after copying
"/usr/local/apache-maven/apache-maven-3.2.1/bin"
b) update the .bash_profile and set the path
    export PATH = {$PATH}: /usr/local/apache-maven/apache-maven-3.2.1/bin
c) type "source ~/.bash_profile” in the terminal window to refresh the .bash_profile.







Installing JDK on Mac OS:
------------------------------------
a) Download and install the latest version of JDK
b) Type the following command on the Terminal
    $ /usr/libexec/java_home -V

c) Now type the following command to check the Java Version
    $java -version







Updating System JDK Version:
-----------------------------------------
System JDK : /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin

Installed JDK : /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin

steps:
--------
a) cd /System/Library/Frameworks/JavaVM.framework/Versions/
b) sudo rm CurrentJDK
c) sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin CurrentJDK





Setting JAVA_HOME environment variable:
---------------------------------------------------------
a) Edit .bash_profile inside  /Users/susantabehera/ folder
b) Type the following to set the environment variable
export JAVA_HOME=$(/usr/libexec/java_home)
c) Reload the .bash_profile by typing the following command on Terminal
source ~/.bash_profile




Tuesday, September 23, 2014

Setting JAVA_HOME environment variable on Mac OS

Steps:
-------
a) Edit .bash_profile inside  /Users/susantabehera/ folder
b) Type the following to set the environment variable
    export JAVA_HOME=$(/usr/libexec/java_home)
c) Reload the .bash_profile by typing the following command on Terminal
    source ~/.bash_profile

Monday, September 22, 2014

Updating JDK on MacOS


Installing JDK on Mac OS:
------------------------------------
a) Download and install the latest version of JDK
b) Type the following command on the Terminal
    $ /usr/libexec/java_home -V

c) Now type the following command on Terminal to check the Java Version
    $java -version




Updating System JDK Version:
-----------------------------------------
System JDK : /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin

Installed JDK : /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin

steps:
--------
a) cd /System/Library/Frameworks/JavaVM.framework/Versions/
b) sudo rm CurrentJDK
c) sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin CurrentJDK


Done !!!


Installing maven on Mac OS

Steps:
-------
a) Copy the maven folder inside "/usr/local” folder , which will look like this after copying
"/usr/local/apache-maven/apache-maven-3.2.1/bin"
b) update the .bash_profile and set the path
    export PATH = {$PATH}: /usr/local/apache-maven/apache-maven-3.2.1/bin
c) type "source ~/.bash_profile” in the terminal window to refresh the .bash_profile.

Parse Linker Error in Other Linker Flags

Do the following:

1.Remove -ObjC and -all_load
2.Add -force_load $(SRCROOT)/GoogleAdmob/fileName.a


Sunday, September 21, 2014

Adjusting extra space at top of UITableView


To remove the extra space on the top of the UITableView ,
add the following code in the ViewDidLoad method of the UIViewController.

- (void)viewDidLoad {
    [super viewDidLoad];
   self.automaticallyAdjustsScrollViewInsets = NO;
 }

Friday, September 19, 2014

NSMutableAttributedString Example



NSString *str = self.view2TextLbl.text;
NSRange range = [str rangeOfString:@"#"];


if(range.location != NSNotFound && range.length){


    UIFont *font1 = [UIFont myAlphaFontsBold:13];
    UIFont *font2 = [UIFont myAlphaFontsBold:14];
   
    UIColor *font1Color = [UIColor whiteColor];
    UIColor *font2Color = [UIColor blackColor];
   
    NSRange range1 = NSMakeRange(0, range.location);
    NSRange range2 = NSMakeRange(range.location, (str.length - range.location));
   
   
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str];
   
    [attributedStr addAttribute:NSFontAttributeName value:font1 range:range1];
    [attributedStr addAttribute:NSFontAttributeName value:font2 range:range2];
   
    [attributedStr addAttribute:NSForegroundColorAttributeName value:font1Color range:range1];
    [attributedStr addAttribute:NSForegroundColorAttributeName value:font2Color range:range2];
   
    self.view2TextLbl.attributedText = attributedStr;
 
}     

NSURLAuthenticationChallenge


#pragma mark - NSURLConnection delegate for Handling HTTPS
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace {
  NSLog(@"Authentication String : %@", NSURLAuthenticationMethodServerTrust);
 
  NSLog(@"protectionSpace.authenticationMethod : %@", protectionSpace.authenticationMethod);
 
  //return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
 
  return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
 
  NSLog(@"challenge.protectionSpace.authenticationMethod : %@", challenge.protectionSpace.authenticationMethod);
 
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    NSLog(@"************ CERTIFICATE DOWNLOADED ***************");
  }
  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
 
}

Android UI - Inflate from XML

   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Button b = (Button)inflater.inflate(R.layout.buttons,
                null);
      
        lLayout = (LinearLayout)findViewById(R.id.layout1);
        lLayout.addView(b);



    b.setOnClickListener(new OnClickListener() {
          
            public void onClick(View v) {
                  //restrict to adding only 1 textview child element
                  if (lLayout.getChildAt(2) == null)
                  {
                  TextView tv = (TextView)inflater.inflate(R.layout.text, null);
                  lLayout.addView(tv);
                  }
            }
        });
  }


Assume, on the click of the button, you want to show some new text. This TextView is defined in another XML called text.xml which is also in the res/layout folder.

Creating Android UI Programmatically


 public void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
     
        lLayout = new LinearLayout(this);
        lLayout.setOrientation(LinearLayout.VERTICAL);
        //-1(LayoutParams.MATCH_PARENT) is fill_parent or match_parent since API level 8
        //-2(LayoutParams.WRAP_CONTENT) is wrap_content
        lLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
        tView = new TextView(this);
        tView.setText("Hello, This is a view created programmatically! " +
                  "You CANNOT change me that easily :-)");
        tView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
        lLayout.addView(tView);
        setContentView(lLayout);
       
  }     

Thursday, September 18, 2014

Identifying iPhone & iPad Models

Identifying iPhone models
http://support.apple.com/kb/HT3939

Identifying iPad models
http://support.apple.com/kb/HT5452

GMT Date

- (NSDate *)dateToGMT:(NSDate *)sourceDate      // To convert current GMT time
{
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate] autorelease];
    return destinationDate;
}


GMT and Localtime in ObjectiveC

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss zzz, zzzz";

  NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  [dateFormatter setTimeZone:gmt];
  NSString *gmtTimeStamp = [dateFormatter stringFromDate:[NSDate date]];
  NSLog(@"GMT Time : %@", gmtTimeStamp);

 
 
  NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
  //NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
  //NSTimeZone *localTimeZone = [NSTimeZone defaultTimeZone];

  [dateFormatter setTimeZone:localTimeZone];
  NSString *localTimeStamp = [dateFormatter stringFromDate:[NSDate date]];
  NSLog(@"Local Time : %@", localTimeStamp);

Date Programming


http://rypress.com/tutorials/objective-c/data-types/dates.html


Wednesday, September 17, 2014

Dismiss Keyboard in Android

private void hideSoftKeyBoard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    if(imm.isAcceptingText()) { // verify if the soft keyboard is open                     
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

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

public static void hideKeyboard(Activity activity) {
    View v = activity.getWindow().getCurrentFocus();
    if (v != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}


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


yourEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if(!hasFocus){
                            hideKeyboard();
                        }

                    }
                });


private void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
}

Reading from External Storage in Android


Reading from External Storage:
---------------———————————————

<manifest >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>



/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}