Saturday, June 14, 2014

Resize Image:


UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
CGSize itemSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[thumbnail drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Loading and Caching Images in UITableViewCell

@interface ViewController : UIViewController
@property (strong ,nonatomic) NSMutableArray *tableItems;
@property (strong ,nonatomic) NSMutableDictionary *cachedImages;

@end


@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.cachedImages = [[NSMutableDictionary alloc] init];
    self.tableItems = [[NSMutableArray alloc] init];
    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.tableitems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
    if(cell == nil){
       
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
    }

    NSString *identifier = [NSString stringWithFormat:@"Cell%d" ,
                            indexPath.row];
   
    if([self.cachedImages objectForKey:identifier] != nil){
        cell.imageView.image = [self.cachedImages valueForKey:identifier];
    }else{
       
        char const * s = [identifier  UTF8String];
       
        dispatch_queue_t queue = dispatch_queue_create(s, 0);
       
        dispatch_async(queue, ^{
           
            NSString *url = @"http://ovidos.com/img/logo.png";
           
            UIImage *img = nil;
           
            NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
           
            img = [[UIImage alloc] initWithData:data];
           
            dispatch_async(dispatch_get_main_queue(), ^{
               
                if ([tableView indexPathForCell:cell].row == indexPath.row) {
                   
                    [self.cachedImages setValue:img forKey:identifier];

                    cell.imageView.image = [self.cachedItems valueForKey:identifier];
                }
            });//end
        });//end
    }
   

    return cell;

}

@end

Adding Shadow Effect:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    redView.layer.cornerRadius = 10;
    redView.layer.shadowColor = [[UIColor blackColor] CGColor];
    redView.layer.shadowOpacity = 1;
    redView.layer.shadowRadius = 10;
    redView.layer.shadowOffset = CGSizeMake(-2, 7);
    [redView setBackgroundColor:[UIColor redColor]];
    redView.center=  CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    [self.view addSubview:redView];  
}

Gradient Backgrounds in iOS

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.view.layer insertSublayer:gradient atIndex:0];

Wednesday, June 11, 2014

Rounded Corners in UIView


    UIView *aView  =   /* Some View */

    CGRect bounds = aView.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;
   
    aView.layer.mask = maskLayer;





Friday, June 6, 2014

MapKit Framework:


#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MapAnnotation : NSObject<MKAnnotation>
@property (nonatomic, strong) NSString *title;
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;

- (id)initWithTitle:(NSString *)title andCoordinate:
  (CLLocationCoordinate2D)coordinate2d;

@end

#import "MapAnnotation.h"

@implementation MapAnnotation
-(id)initWithTitle:(NSString *)title andCoordinate:
 (CLLocationCoordinate2D)coordinate2d{   
    self.title = title;
    self.coordinate =coordinate2d;
    return self;
}
@end

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

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<MKMapViewDelegate>
{
    MKMapView *mapView;
}
@end


#import "ViewController.h"
#import "MapAnnotation.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
   [super viewDidLoad];
  
   mapView = [[MKMapView alloc]initWithFrame:
   CGRectMake(10, 100, 300, 300)];
   mapView.delegate = self;
   mapView.centerCoordinate = CLLocationCoordinate2DMake(37.32, -122.03);
   mapView.mapType = MKMapTypeHybrid;
  
  
   CLLocationCoordinate2D location;
   location.latitude = (double) 37.332768;
   location.longitude = (double) -122.030039;
   // Add the annotation to our map view
   MapAnnotation *newAnnotation = [[MapAnnotation alloc]
   initWithTitle:@"Apple Head quaters" andCoordinate:location];
   [mapView addAnnotation:newAnnotation];
  
  
   CLLocationCoordinate2D location2;
   location2.latitude = (double) 37.35239;
   location2.longitude = (double) -122.025919;
   MapAnnotation *newAnnotation2 = [[MapAnnotation alloc]
   initWithTitle:@"Test annotation" andCoordinate:location2];
   [mapView addAnnotation:newAnnotation2];
  
   [self.view addSubview:mapView];
}


// When a map annotation point is added, zoom to it (1500 range)
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
   MKAnnotationView *annotationView = [views objectAtIndex:0];
   id <MKAnnotation> mp = [annotationView annotation];
   MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance
   ([mp coordinate], 1500, 1500);
   [mv setRegion:region animated:YES];
   [mv selectAnnotation:mp animated:YES];
}

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

@end

GameKit Framework


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

@interface ViewController : UIViewController<GKLeaderboardViewControllerDelegate>

-(IBAction)updateScore:(id)sender;
-(IBAction)showLeaderBoard:(id)sender;

@end


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if([GKLocalPlayer localPlayer].authenticated == NO)
    {
      [[GKLocalPlayer localPlayer]
      authenticateWithCompletionHandler:^(NSError *error)
      {
         NSLog(@"Error%@",error);
      }];
    }   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void) updateScore: (int64_t) score
forLeaderboardID: (NSString*) category
{
    GKScore *scoreObj = [[GKScore alloc]
    initWithCategory:category];
    scoreObj.value = score;
    scoreObj.context = 0;
    [scoreObj reportScoreWithCompletionHandler:^(NSError *error) {
        // Completion code can be added here
        UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:nil message:@"Score Updated Succesfully"
        delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];

    }];
}
-(IBAction)updateScore:(id)sender{
    [self updateScore:200 forLeaderboardID:@"tutorialsPoint"];
}
-(IBAction)showLeaderBoard:(id)sender{
    GKLeaderboardViewController *leaderboardViewController =
    [[GKLeaderboardViewController alloc] init];
    leaderboardViewController.leaderboardDelegate = self;
    [self presentModalViewController:
    leaderboardViewController animated:YES];

}
#pragma mark - Gamekit delegates
- (void)leaderboardViewControllerDidFinish:
(GKLeaderboardViewController *)viewController{
    [self dismissModalViewControllerAnimated:YES];
}

@end


Adding Toolbar:


-(void)addToolbar
{
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
    target:nil action:nil];

    UIBarButtonItem *customItem1 = [[UIBarButtonItem alloc]
    initWithTitle:@"Tool1" style:UIBarButtonItemStyleBordered
    target:self action:@selector(toolBarItem1:)];

    UIBarButtonItem *customItem2 = [[UIBarButtonItem alloc]
    initWithTitle:@"Tool2" style:UIBarButtonItemStyleDone
    target:self action:@selector(toolBarItem2:)];

    NSArray *toolbarItems = [NSArray arrayWithObjects:
    customItem1,spaceItem, customItem2, nil];

    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:
    CGRectMake(0, 366+54, 320, 50)];
    [toolbar setBarStyle:UIBarStyleBlackOpaque];
    [self.view addSubview:toolbar];

    [toolbar setItems:toolbarItems];
}


-(IBAction)toolBarItem1:(id)sender{
    [label setText:@"Tool 1 Selected"];
}

-(IBAction)toolBarItem2:(id)sender{
    [label setText:@"Tool 2 Selected"];   
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // The method hideStatusbar called after 2 seconds

    [self addToolbar];   
    // Do any additional setup after loading the view, typically from a nib.
}


Tuesday, June 3, 2014

Text 2 Speech in iOS 7.0

AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@"Hey there!"];
[synthesizer speakUtterance:utterance];

Sending JSON Data using NSURLConnection:


NSString *jsonPostBody = [NSString stringWithFormat:@"'json' = '{\"user\":{\"username\":"
                          "\"%@\""
                          ",\"password\":"
                          "\"%@\""
                          "}}'",
                          [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                          [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];      
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *apiPathParams = [NSString stringWithFormat:@"%@",
                           @"getUser"
                           ];

NSURL *url = [NSURL URLWithString:[[apiPath retain] stringByAppendingString:apiPathParams]];   
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:180.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];
[self internalRequest:request];


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


NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nil];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
[request setValue:[NSString stringWithFormat:@"%d", [loginDataJSON length]] forHTTPHeaderField:@"content-length"];
//[request setHTTPBody:loginDataJSON];

[request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                      dataUsingEncoding:NSUTF8StringEncoding
                   allowLossyConversion:YES]]; 
                  
                  

JSON String to NSDictionary:

NSDictionary *JSON =  [NSJSONSerialization JSONObjectWithData: [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding]
                                    options: NSJSONReadingMutableContainers
                                      error: &e];
                                     
                                     
                                     

Calculating Distance between 2 locations:


CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
CLLocationDistance km = [newLocation distanceFromLocation:oldLocation]/1000;

Customizing the Title Text of Navigation Bar:

UITextAttributeFont – Key to the font
UITextAttributeTextColor – Key to the text color
UITextAttributeTextShadowColor – Key to the text shadow color
UITextAttributeTextShadowOffset – Key to the offset used for the text shadow

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

    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], UITextAttributeTextColor,
                                                           [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],UITextAttributeTextShadowColor,
                                                           [NSValue valueWithUIOffset:UIOffsetMake(0, 1)],
                                                           UITextAttributeTextShadowOffset,
                                                           [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], UITextAttributeFont, nil]];

Reverse GeoCoding using GoogleMaps in JavaScript

function getLatLong(address){
      var geo = new google.maps.Geocoder;

      geo.geocode({'address':address},function(results, status){
              if (status == google.maps.GeocoderStatus.OK) {
                return results[0].geometry.location;
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }

       });

  }
 

Adding Projects to GitHub

git init
git add .
git commit -m "Initial commit"
git push -u origin master


Google Translate API


<?php
$api_key = 'PUT_YOUR_SERVER_KEY_HERE';
$text = 'How are you';
$source="en";
$target="fr";

$url = 'https://www.googleapis.com/language/translate/v2?key=' . $api_key . '&q=' . rawurlencode($text);
$url .= '&target='.$target;
$url .= '&source='.$source;

$response = file_get_contents($url);
$obj =json_decode($response,true); //true converts stdClass to associative array.
if($obj != null)
{
    if(isset($obj['error']))
    {
        echo "Error is : ".$obj['error']['message'];
    }
    else
    {
        echo "Translsated Text: ".$obj['data']['translations'][0]['translatedText']."\n";
    }
}
else
    echo "UNKNOW ERROR";

?>

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


Google Translate API ( PHP CURL ):
=================================

<?php
$api_key = 'PUT_YOUR_SERVER_KEY_HERE';
$text = 'How are you';
$source="en";
$target="fr";

$obj = translate($api_key,$text,$target,$source);
if($obj != null)
{
    if(isset($obj['error']))
    {
        echo "Error is : ".$obj['error']['message'];
    }
    else
    {
        echo "Translsated Text: ".$obj['data']['translations'][0]['translatedText']."\n";
        if(isset($obj['data']['translations'][0]['detectedSourceLanguage'])) //this is set if only source is not available.
            echo "Detecte Source Languge : ".$obj['data']['translations'][0]['detectedSourceLanguage']."\n";      
    }
}
else
    echo "UNKNOW ERROR";

function translate($api_key,$text,$target,$source=false)
{
    $url = 'https://www.googleapis.com/language/translate/v2?key=' . $api_key . '&q=' . rawurlencode($text);
    $url .= '&target='.$target;
    if($source)
     $url .= '&source='.$source;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);               
    curl_close($ch);

    $obj =json_decode($response,true); //true converts stdClass to associative array.
    return $obj;


?>

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


Google Translate API ( GET Request ):
====================================
https://www.googleapis.com/language/translate/v2/detect?key={YOUR_API_KEY}&q=Wie%20geht%20es%20Ihnen


Multiple 'q' parameters:
========================
https://www.googleapis.com/language/translate/v2?key={YOUR_API_KEY}&source=en&target=de&q=Hello%20Ravi&q=How%20are%20you&q=I%20am%20fine









Key-Value Observations in ObjC



// MyClass1.h:
    @interface MyClass1 : NSObject
    @property (nonatomic, copy) NSString* value;
    @end
    // MyClass2.m:
    - (void) observeValueForKeyPath:(NSString *)keyPath
                           ofObject:(id)object
                             change:(NSDictionary *)change
                            context:(void *)context {
        NSLog(@"I heard about the change!");
    }
   
    // Somewhere else entirely:
    MyClass1* objectA = [MyClass1 new];
    MyClass2* objectB = [MyClass2 new];
   
    // register for KVO
    [objectA addObserver:objectB forKeyPath:@"value" options:0 context:nil];
   
    // change the value in a KVO compliant way
    objectA.value = @"Hello, world!";
    // result: objectB's observeValueForKeyPath:... is called
   
--------------------------------------------------------------------

objectA.value = @"Hello";
[objectA addObserver:objectB forKeyPath:@"value" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context: nil];
objectA.value = @"Goodbye"; // notification is triggered
   
   
- (void) observeValueForKeyPath:(NSString *)keyPath
                           ofObject:(id)object
                             change:(NSDictionary *)change
                            context:(void *)context {
        id newValue = change[NSKeyValueChangeNewKey];
        id oldValue = change[NSKeyValueChangeOldKey];
        NSLog(@"The key path %@ changed from %@ to %@",
              keyPath, oldValue, newValue);
}

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

Starting a background task at quit time


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

    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{

        // Clean up any unfinished task business by marking where you

        // stopped or ending the task outright.

        [application endBackgroundTask:bgTask];

        bgTask = UIBackgroundTaskInvalid;

    }];



    // Start the long-running task and return immediately.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{



        // Do the work associated with the task, preferably in chunks.



        [application endBackgroundTask:bgTask];

        bgTask = UIBackgroundTaskInvalid;

    });

}

Push Notification Server Side Code in PHP

<?php

$url = 'https://gateway.sandbox.push.apple.com:2195';
$cert = 'AppCert.pem';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $cert);
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, "passphrase");
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"device_tokens": ["458e5939b2xxxxxxxxxxx3"], "aps": {"alert": "test message one!"}}');

$curl_scraped_page = curl_exec($ch);

?>

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

<?php

// Create a stream to the server
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', 'apns-dev.pem');

$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

// You can access the errors using the variables $error and $errorString

$message = 'You have just pushed data via APNS';

// Now we need to create JSON which can be sent to APNS

$load = array(    'aps' => array(
                'alert' => $message,
                'badge' => 1,
                'sound' => 'default'
                )
            );

$payload = json_encode($load);

// The payload needs to be packed before it can be sent

$apnsMessage = chr(0) . chr(0) . chr(32);
$apnsMessage .= pack('H*', str_replace(' ', '', $token));
$apnsMessage .= chr(0) . chr(strlen($payload)) . $payload;


// Write the payload to the APNS

fwrite($apns, $apnsMessage);
echo "just wrote " . $payload;

// Close the connection
fclose($apns);

?>


Thursday, May 22, 2014

Shuffling NSMutableArray

@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end


//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{
    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n = arc4random_uniform(nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

@end