Monday, June 30, 2014

Scanning Barcodes in iOS 7

Add the AVFoundation Framework in iOS 7.0


- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    CGRect highlightViewRect = CGRectZero;
    AVMetadataMachineReadableCodeObject *barCodeObject;
    NSString *detectionString = nil;
    NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
            AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
            AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];

    for (AVMetadataObject *metadata in metadataObjects) {
        for (NSString *type in barCodeTypes) {
            if ([metadata.type isEqualToString:type])
            {
                barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
                highlightViewRect = barCodeObject.bounds;
                detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
                break;
            }
        }

        if (detectionString != nil)
        {
            _label.text = detectionString;
            break;
        }
        else
            _label.text = @"(none)";
    }

    _highlightView.frame = highlightViewRect;
}

Getting Speed using CoreLocation Framework in iOS

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *loc = locations.lastObject;
    double speed = loc.speed;
    NSLog(@"%f", speed);
}

Wednesday, June 25, 2014

Utility for ObjC



#import <Foundation/Foundation.h>
@interface Utility : NSObject

+(BOOL)isiPhone5;
+(void)addGradientToView : (UIView *)aView
        withStartingColor:(UIColor *)startColor
              endingColor:(UIColor *)endColor;


+(UIImage *)resizeImage:(UIImage *)aImage toSize:(CGSize)size;


@end



#import "Utility.h"

@implementation Utitlity

+(BOOL)isiPhone5 {
 
  BOOL result = NO;
 
  if([[UIScreen mainScreen] bounds].size.height == 568.0f) {
    result = YES;
    NSLog(@"iPhone 5");
  } else {
    NSLog(@"iPhone 4");
  }
 
  return result;
}


+(void)addGradientToView : (UIView *)aView withStartingColor:(UIColor *)startColor endingColor:(UIColor *)endColor {
 
  CAGradientLayer *gradient = [CAGradientLayer layer];
  gradient.frame  = aView.bounds;
  gradient.colors = [NSArray arrayWithObjects:(id)[startColor CGColor], (id)[endColor CGColor], nil];
  [aView.layer insertSublayer:gradient atIndex:0];
}


+(UIImage *)resizeImage:(UIImage *)aImage toSize:(CGSize)size {
 
  UIImage *resultImage = nil;
 
  UIGraphicsBeginImageContext(size);
  CGRect imageRect = CGRectMake(0.0, 0.0, size.width, size.height);
  [aImage drawInRect:imageRect];
  resultImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
 
  return resultImage;
}


@end



Monday, June 23, 2014

Date Programming




The above diagram provides a high-level overview of Objective-C’s date-handling capabilities. The NSDate class represents a specific point in time, which can be reduced to NSDateComponent’s (e.g., days, weeks, years) by interpreting it in the context of an NSCalendar object. The NSDateFormatter class provides a human-readable version of an NSDate, and NSLocale and NSTimeZone encapsulate essential localization information for many calendrical operations.
This module explains all of this in much more detail using several hands-on examples. By the end of this module, you should be able to perform any kind of date operation that you’ll ever need.

NSDate

An NSDate object represents a specific point in time, independent of any particular calendrical system, time zone, or locale. Internally, it just records the number of seconds from an arbitrary reference point (January 1st, 2001 GMT). For a date to be useful, it generally needs to be interpreted in the context of an NSCalendar object.
NSDate recording the number of seconds from its reference point
You’ll typically want to create date objects using a calendar or a date formatter, as the NSDate class only provides a few low-level methods for creating dates from scratch. The date method returns an object representing the current date and time, and dateWithTimeInterval:sinceDate: generates a relative date using an NSTimeInterval, which is a double storing the number of seconds from the specified date. As you can see in the following example, a positive interval goes forward in time, and a negative one goes backwards.

NSDate *now = [NSDate date];
NSTimeInterval secondsInWeek = 7 * 24 * 60 * 60;
NSDate *lastWeek = [NSDate dateWithTimeInterval:-secondsInWeek
                                      sinceDate:now];
NSDate *nextWeek = [NSDate dateWithTimeInterval:secondsInWeek
                                      sinceDate:now];
NSLog(@"Last Week: %@", lastWeek);
NSLog(@"Right Now: %@", now);
NSLog(@"Next Week: %@", nextWeek); 
 
This will output three datetime strings that look something like 2012-11-06 02:24:00 +0000. They contain the date (expressed as year-month-date), the time of day (expressed as hours:minutes:seconds) and the time zone (expressed as an offset from Greenwich Mean Time (GMT)).

Aside from capturing an absolute point in time, the only real job of NSDate is to facilitate comparisons. It defines isEqualToDate: and compare: methods, which work just like the ones provided by NSNumber. In addition, the earlierDate: and laterDate: methods can be used as a convenient shortcut.

NSComparisonResult result = [now compare:nextWeek];
if (result == NSOrderedAscending) {
    NSLog(@"now < nextWeek");
} else if (result == NSOrderedSame) {
    NSLog(@"now == nextWeek");
} else if (result == NSOrderedDescending) {
    NSLog(@"now > nextWeek");
}
NSDate *earlierDate = [now earlierDate:lastWeek];
NSDate *laterDate = [now laterDate:lastWeek];
NSLog(@"%@ is earlier than %@", earlierDate, laterDate);

NSDateComponents

The NSDateComponents class is a simple data structure for representing the various time periods used by a calendrical system (days, weeks, months, years, etc). Unlike NSDate, the meaning of these components are entirely dependent on how it’s used.

Consider an NSDateComponents object with its year property set to 2012. This could be interpreted as the year 2012 by a Gregorian calendar, the year 1469 by a Buddhist calendar, or two thousand and twelve years relative to some other date.

We’ll work more with date components in the next section, but as a simple example, here’s how you would create an NSDateComponents instance that could be interpreted as November 4th, 2012:

NSDateComponents *november4th2012 = [[NSDateComponents alloc] init];
[november4th2012 setYear:2012];
[november4th2012 setMonth:11];
[november4th2012 setDay:4];
NSLog(@"%@", november4th2012); 
 
Again, it’s important to understand that these components don’t actually represent November 4th, 2012 until it is interpreted by a Gregorian calendar object as such.

The complete list of component fields can be found below. Note that it’s perfectly legal to set only the properties you need and leave the rest as NSUndefinedDateComponent, which is the default value for all fields.
era week
year weekday
month weekdayOrdinal
day quarter
hour weekOfMonth
minute weekOfYear
second yearForWeekOfYear

NSCalendar

A calendrical system is a way of breaking down time into manageable units like years, months, weeks, etc. These units are represented as NSDateComponents objects; however, not all systems use the same units or interpret them in the same way. So, an NSCalendar object is required to give meaning to these components by defining the exact length of a year/month/week/etc.
This provides the necessary context for translating absolute NSDate instances into NSDateComponents. This is a very important ability, as it lets you work with dates on an intuitive, cultural level instead of a mathematical one. That is, it’s much easier to say, “November 4th, 2012” than “373698000 seconds after January 1st, 2001.”
Using NSCalendar to convert between dates and date components
This section explains how to create different types of calendars, then covers the three main responsibilities of NSCalendar: converting NSDate objects to components, creating NSDate objects from components, and performing calendrical calculations. We’ll also take a brief look at NSCalendarUnit.

Creating Calendars

NSCalendar’s initWithCalendarIdentifier: initializer accepts an identifier that defines the calendrical system to use. In addition, the currentCalendar class method returns the user’s preferred calendar. For most applications, you should opt for currentCalendar instead of manually defining one, since it reflects the user’s device settings.

NSCalendar *gregorian = [[NSCalendar alloc]
                    initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendar *buddhist = [[NSCalendar alloc]
                    initWithCalendarIdentifier:NSBuddhistCalendar];
NSCalendar *preferred = [NSCalendar currentCalendar];
NSLog(@"%@", gregorian.calendarIdentifier);
NSLog(@"%@", buddhist.calendarIdentifier);
NSLog(@"%@", preferred.calendarIdentifier); 
 
The calendarIdentifier method lets you display the string-representation of the calendar ID, but it is read-only (you can’t change the calendrical system after instantiation). The rest of Cocoa’s built-in calendar identifiers can be accessed via the following constants:

NSGregorianCalendar NSBuddhistCalendar
NSChineseCalendar NSHebrewCalendar
NSIslamicCalendar NSIslamicCivilCalendar
NSJapaneseCalendar NSRepublicOfChinaCalendar
NSPersianCalendar NSIndianCalendar
NSISO8601Calendar
The next few sections walk through the basic usage of NSCalendar. If you change the identifier, you can see how different calendars have different interpretations of date components.

From Dates to Components

The following example shows you how to convert an NSDate into a culturally significant NSDateComponents object.
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc]
                        initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:now];

NSLog(@"Day: %ld", [components day]);
NSLog(@"Month: %ld", [components month]);
NSLog(@"Year: %ld", [components year]);
 
First, this creates an NSCalendar object that represents a Gregorian calendar. Then, it creates a bitmask defining the units to include in the conversion (see NSCalendarUnits for details). Finally, it passes these units and an NSDate to the components:fromDate: method.

From Components to Dates

A calendar can also convert in the other direction, which offers a much more intuitive way to create NSDate objects. It lets you define a date using the components of your native calendrical system:

NSCalendar *calendar = [[NSCalendar alloc]
                    initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2012];
[components setMonth:11];
[components setDay:4];

NSDate *november4th2012 = [calendar dateFromComponents:components];
NSLog(@"%0.0f seconds between Jan 1st, 2001 and Nov 4th, 2012",
          [november4th2012 timeIntervalSinceReferenceDate]); 
 
It’s not necessary to define the units to include in the conversion, so this is a little more straightforward than translating dates to components. Simply instantiate an NSDateComponents object, populate it with the desired components, and pass it to the dateFromComponents: method.
Remember that NSDate represents an absolute point in time, independent of any particular calendrical system. So, by calling dateFromComponents: on different NSCalendar objects, you can reliably compare dates from incompatible systems.

Calendrical Calculations

The third job of NSCalendar is to provide a high-level API for date-related calculations. First, we’ll take a look at how calendars let you add components to a given NSDate instance. The following example generates a date object that is exactly one month away from the current date.

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc]
                    initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMonth:1];
NSDate *oneMonthFromNow = [calendar dateByAddingComponents:components
                                                    toDate:now
                                                   options:0];
NSLog(@"%@", oneMonthFromNow); 
 
All you have to do is create an NSDateComponents object, record the components you want to add, and pass it to dateByAddingComponents:toDate:options:. This is a good example of how the meaning of date components is entirely dependent on how it’s used. Instead of representing a date, the above components represent a duration.

The options argument should either be 0 to let components overflow into higher units or NSWrapCalendarComponents to prevent this behavior. For example, if you set month to 14, passing 0 as an option tells the calendar to interpret it as 1 year and 2 months, whereas NSWrapCalendarComponents interprets it as 2 months and completely ignores the extra year.

Also note that dateByAddingComponents:toDate:options: is a calendar-aware operation, so it compensates for 30 vs. 31 day months (in the Gregorian calendar). This makes NSCalendar a more robust way of adding dates than NSDate’s low-level dateWithTimeInterval:sinceDate: method.

The other major calendrical operation provided by NSCalendar is components:fromDate:toDate:options:, which calculates the interval between two NSDate objects. For example, you can determine the number of weeks since NSDate’s internal reference point as follows:
NSDate *start = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
NSDate *end = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit units = NSWeekCalendarUnit;
NSDateComponents *components = [calendar components:units
                                           fromDate:start
                                             toDate:end
                                            options:0];
NSLog(@"It has been %ld weeks since January 1st, 2001",
      [components week]);

NSCalendarUnit

The first argument of components:fromDate: and components:fromDate:toDate:options: determine the properties that will be populated on the resulting NSDateComponents object. The possible values are defined by NSCalendarUnit, which enumerates the following constants:

NSEraCalendarUnit NSWeekdayCalendarUnit
NSYearCalendarUnit NSWeekdayOrdinalCalendarUnit
NSMonthCalendarUnit NSQuarterCalendarUnit
NSDayCalendarUnit NSWeekOfMonthCalendarUnit
NSHourCalendarUnit NSWeekOfYearCalendarUnit
NSMinuteCalendarUnit NSYearForWeekOfYearCalendarUnit
NSSecondCalendarUnit NSCalendarCalendarUnit
NSWeekCalendarUnit NSTimeZoneCalendarUnit   
When you need more than one of these units, you should combine them into a bitmask using the bitwise OR operator (|). For example, to include the day, hour, and minute, you would use the following value for the first parameter of components:fromDate:.
NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit

NSDateFormatter

The NSDateFormatter class makes it easy to work with the human-readable form of a date. Whereas calendars decompose a date into an NSDateComponents object, date formatters convert between NSDate’s and NSString’s.
Using a NSDateFormatter to convert between dates and strings
There are two ways to use a date formatter: 1) with localized styles or 2) with a custom format string. The former method is a better choice if you’re displaying content to users, since it incorporates their preferences and device settings. The latter is useful when you need to know exactly what the resulting string representations will look like.

Localized Styles

Localized styles define how a date should look using abstract descriptions instead of specific date components. For example, instead of defining a date as MM/dd/yy, a style would say it should be displayed in its “short” form. This lets the system adapt the representation to the user’s language, region, and preferences while still offering a level of control to the developer.

The following snippet formats a date using the “short” style. As you can see, separate styles are used for the date and the time. The stringFromDate: method formats an NSDate object according to the provided styles.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];

NSDate *now = [NSDate date];
NSString *prettyDate = [formatter stringFromDate:now];
NSLog(@"%@", prettyDate);
 
I’m an English speaker from the United States, so this will output 11/4/2012 8:09 PM. If you have different default settings, you’ll see the traditional date formatting used in your particular language/region. We’ll take a closer look at this behavior in the NSLocale section. The complete list of formatting styles are included below.
NSDateFormatterNoStyle
NSDateFormatterShortStyle
NSDateFormatterMediumStyle
NSDateFormatterLongStyle
NSDateFormatterFullStyle
Note that the NSDateFormatterNoStyle constant can be used to omit the date or time from the output string.

Custom Format Strings

Again, the styles discussed above are the preferred way to define user-visible dates. However, if you’re working with dates on a programmatic level, you may find the setDateFormat: method useful. This accepts a format string that defines precisely how the date will appear. For example, you can use M.d.y to output the month, date, and year separated by periods as follows:

// Formatter configuration
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:posix];
[formatter setDateFormat:@"M.d.y"]; 
 
// Date to string
NSDate *now = [NSDate date];
NSString *prettyDate = [formatter stringFromDate:now];
NSLog(@"%@", prettyDate); 
 
As a best practice, you should always set the locale property of the NSDateFormatter before using custom format strings. This ensures that the user’s default locale won’t affect the output, which would result in subtle, hard-to-reproduce bugs. In the above case, the POSIX locale ensures that the date is displayed as 11.4.2012, regardless of the user’s settings.

Custom date formats also present an alternative way to create date objects. Using the above configuration, it’s possible to convert the string 11.4.2012 into an NSDate with the dateFromString: method. If the string cant’t be parsed, it will return nil.

// String to date
NSString *dateString = @"11.4.2012";
NSDate *november4th2012 = [formatter dateFromString:dateString];
NSLog(@"%@", november4th2012); 
 
In addition to M, d, and y, the Unicode Technical Standard #35 defines a plethora of other date format specifiers. This document contains a lot of information not really necessary to use NSDateFormatter correctly, so you may find the following list of sample format strings to be a more practical quick-reference. The date used to generate the output string is November 4th, 2012 8:09 PM Central Standard Time.
Format String Output String
M/d/y 11/4/2012
MM/dd/yy 11/04/12
MMM d, ''yy Nov 4, '12
MMMM November
E Sun
EEEE Sunday
'Week' w 'of 52' Week 45 of 52
'Day' D 'of 365' Day 309 of 365
QQQ Q4
QQQQ 4th quarter
m 'minutes past' h 9 minutes past 8
h:mm a 8:09 PM
HH:mm:ss's' 20:09:00s
HH:mm:ss:SS 20:09:00:00
h:mm a zz 8:09 PM CST
h:mm a zzzz 8:09 PM Central Standard Time
yyyy-MM-dd HH:mm:ss Z 2012-11-04 20:09:00 -0600
Notice that literal text needs to be wrapped in single quotes to prevent it from being parsed by the formatter.

NSLocale

An NSLocale object represents a set of conventions for a particular language, region, or culture. Both NSCalendar and NSDateFormatter rely on this information to localize many of their core operations.
The previous section already showed you how to create a custom locale via the initWithLocaleIdentifier: initializer. Let’s take a look at the impact a locale change can have on an NSDateFormatter by running the same example using Egyptian Arabic instead of POSIX:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *egyptianArabic = [[NSLocale alloc] initWithLocaleIdentifier:@"ar_EG"];
[formatter setLocale:egyptianArabic];
[formatter setDateFormat:@"M.d.y"];

NSDate *now = [NSDate date];
NSString *prettyDate = [formatter stringFromDate:now];
NSLog(@"%@", prettyDate); 
 
Instead of 11.4.2012, the date is now displayed with Arabic digits: ١١.Ù¤.٢٠١٢. This is why setting the locale before using custom format strings is so important—if you don’t, NSDateFormatter will use the system default, and your format strings will return unexpected results for international users.

Locale identifiers are composed of a language abbreviation followed by a country abbreviation. In the above example, ar stands for Arabic, and EG represents the Egyptian dialect. You can obtain a complete list of available locale identifiers with the following (it’s a very long list):
NSLog(@"%@", [NSLocale availableLocaleIdentifiers]); 
 
But, whenever possible, you’ll want to stick with the user’s preferred locale. This makes sure that your app conforms to their expectations (you don’t want to force an Arabic speaker to read English). You can access the preferred locale through the currentLocale class method, as shown below. Note that this is the default used by NSCalendar and NSDateFormatter.

NSLocale *preferredLocale = [NSLocale currentLocale]); 
 
Custom NSLocale objects are usually only required for specialized applications or testing purposes, but it’s still good to understand how iOS and OS X applications automatically translate your data for an international audience.

NSTimeZone

It’s very important to understand that a string like 11.4.2012 8:09 PM does not specify a precise point in time—8:09 PM in Chicago occurs 8 hours after 8:09 PM in Cairo. The time zone is a required piece of information for creating an absolute NSDate instance. Accordingly, NSCalendar and NSDateFormatter both require an NSTimeZone object to offset their calculations appropriately.

A time zone can be created explicitly with either its full name or its abbreviated one. The following example demonstrates both methods and shows how a time zone can alter the NSDate produced by a formatter. The generated dates are displayed in Greenwich Mean Time, and you can see that 8:09 PM in Chicago is indeed 8 hours after 8:09 PM in Cairo.

NSTimeZone *centralStandardTime = [NSTimeZone timeZoneWithAbbreviation:@"CST"];
NSTimeZone *cairoTime = [NSTimeZone timeZoneWithName:@"Africa/Cairo"];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:posix];
[formatter setDateFormat:@"M.d.y h:mm a"];
NSString *dateString = @"11.4.2012 8:09 PM";

[formatter setTimeZone:centralStandardTime];
NSDate *eightPMInChicago = [formatter dateFromString:dateString];
NSLog(@"%@", eightPMInChicago);      // 2012-11-05 02:09:00 +0000

[formatter setTimeZone:cairoTime];
NSDate *eightPMInCairo = [formatter dateFromString:dateString];
NSLog(@"%@", eightPMInCairo);        // 2012-11-04 18:09:00 +0000 
 
Note that the NSDateFormatter’s timeZone property is a fallback, so format strings that contain one of the z specifiers will use the parsed value as expected. You can use NSCalendar’s timeZone property to the same effect.


Complete lists of time zone names and abbreviations can be accessed via knownTimeZoneNames and abbreviationDictionary, respectively. However, the latter does not necessarily provide values for every time zone.
NSLog(@"%@", [NSTimeZone knownTimeZoneNames]);
NSLog(@"%@", [NSTimeZone abbreviationDictionary]); 
 
All users have a preferred time zone, whether it’s configured explicitly or determined automatically based on their region. The localTimeZone class method is the best option for accessing the current time zone.

NSTimeZone *preferredTimeZone = [NSTimeZone localTimeZone];
As with locales, it’s generally a better idea to stick with the default time zone. Custom NSTimeZone objects are typically only necessary for scheduling applications where time zones need to be explicitly associated with individual events.

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

 

Sunday, June 22, 2014

NSDate​Components Example


(a) Extracting Components From Dates

    Example:
    --------
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [NSDate date];
    [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:date];



(b) Relative Date Calculations
   
    NSDateComponents objects can be used to do relative date calculations. To determining the date yesterday, next week, or 5 hours and 30 minutes from now, use NSCalendar -dateByAddingComponents:toDate:options::

    Example:
    --------
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [NSDate date];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setWeek:1];
    [components setHour:12];

    NSLog(@"1 week and twelve hours from now: %@", [calendar dateByAddingComponents:components toDate:date options:0]);


(c) Creating Dates from Components

    Example:
    --------
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:1987];
    [components setMonth:3];
    [components setDay:17];
    [components setHour:14];
    [components setMinute:20];
    [components setSecond:0];

    NSLog(@"Awesome time: %@", [calendar dateFromComponents:components]);

NSDictionary to JSON String

NSError * err;
NSDictionary *myDictionary = /* Some Dictionary */
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


Wednesday, June 18, 2014

Running Tasks in Background Thread :

//Start an activity indicator here

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Call your function or whatever work that needs to be done
    //Code in this part is run on a background thread

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        //Stop your activity indicator or anything else with the GUI
        //Code here is run on the main thread

    });
});

Saturday, June 14, 2014

GoogleMaps Reverse Geocoding:

#import <GoogleMaps/GoogleMaps.h>

@interface GeocoderViewController : UIViewController

@end

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

@implementation GeocoderViewController {
  GMSMapView *mapView_;
  GMSGeocoder *geocoder_;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
                                                          longitude:151.2086
                                                               zoom:12];

  mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  mapView_.delegate = self;

  geocoder_ = [[GMSGeocoder alloc] init];

  self.view = mapView_;
}

- (void)mapView:(GMSMapView *)mapView
    didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate {
  // On a long press, reverse geocode this location.
  GMSReverseGeocodeCallback handler = ^(GMSReverseGeocodeResponse *response, NSError *error) {
    GMSAddress *address = response.firstResult;
    if (address) {
      NSLog(@"Geocoder result 123 : %@", address);

      GMSMarker *marker = [GMSMarker markerWithPosition:address.coordinate];

      marker.title = [[address lines] firstObject];
      if ([[address lines] count] > 1) {
        marker.snippet = [[address lines] objectAtIndex:1];
      }

      marker.appearAnimation = kGMSMarkerAnimationPop;
      marker.map = mapView_;
    } else {
      NSLog(@"Could not reverse geocode point (%f,%f): %@",
            coordinate.latitude, coordinate.longitude, error);
    }
  };
  [geocoder_ reverseGeocodeCoordinate:coordinate completionHandler:handler];
}

@end


CountryCodes and CountryName in iOS:

NSArray *countryCodes = [NSLocale ISOCountryCodes];
NSMutableArray *countries = [NSMutableArray arrayWithCapacity:[countryCodes count]];

for (NSString *countryCode in countryCodes)
{
    NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
   
    NSString *country = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] displayNameForKey: NSLocaleIdentifier value: identifier];
    [countries addObject: country];
}

NSDictionary *codeForCountryDictionary = [[NSDictionary alloc] initWithObjects:countryCodes forKeys:countries];

Carrier Name in iOS


#import <CoreTelephony/CoreTelephony.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  CTTelephonyNetworkInfo *myNetworkInfo = [[CTTelephonyNetworkInfo alloc] init];
  CTCarrier *carrier = [myNetworkInfo subscriberCellularProvider];

// Get carrier name
NSString *carrierName = [carrier carrierName];
if (carrierName != nil)
  NSLog(@"Carrier: %@", carrierName);

// Get mobile country code
NSString *mcc = [carrier mobileCountryCode];
if (mcc != nil)
  NSLog(@"Mobile Country Code (MCC): %@", mcc); //310

// Get mobile network code
NSString *mnc = [carrier mobileNetworkCode];
if (mnc != nil)
  NSLog(@"Mobile Network Code (MNC): %@", mnc); //410

  // ...
  return YES;
}

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

?>