Wednesday, December 26, 2012

How to check Multitasking capablity in iOS ?

- (BOOL) isMultitaskingCapable
{
 UIDevice* device = [UIDevice currentDevice];
 BOOL backgroundSupported = NO;
 if ([device respondsToSelector:@selector(isMultitaskingSupported)])
  backgroundSupported = device.multitaskingSupported;
 
 return backgroundSupported;
}

How to check Retina display available in phone ?

+ (BOOL) isRetinaDisplay
{
 int scale = 1.0;
 UIScreen *screen = [UIScreen mainScreen];
 if([screen respondsToSelector:@selector(scale)])
  scale = screen.scale;
 
 if(scale == 2.0f) return YES;
 else return NO;
}

Monday, December 10, 2012

Android JSON Parser Example



The first thing we will do is setup our JSON string, which we'll end up parsing.
 
String jsonStr = '{"menu": {' + 
            '"id": "file",' + 
            '"value": "File",' + 
            '"popup": {' + 
              '"menuitem": [' + 
                '{"value": "New", "onclick": "CreateNewDoc()"},' + 
                '{"value": "Open", "onclick": "OpenDoc()"},' + 
                '{"value": "Close", "onclick": "CloseDoc()"}' + 
              ']' + 
            '}' + 
          '}}'


import org.json.JSONObject;

JSONObject jsonObj = new JSONObject(jsonStr);

With that instantiated, we can do the following to retreive different pieces of data from the JSON string - you will also need the following import for JSONArray:import org.json.JSONArray; and import android.util.Log; for Log.



// grabbing the menu object 
JSONObject menu = jsonObj.getJSONObject("menu"); 
 
// these 2 are strings 
String id = menu.getString("id"); 
String value = menu.getString("value"); 
 
// the popop is another JSON object 
JSONObject popup = menu.getJSONObject("popup"); 
 
// using JSONArray to grab the menuitems from under popop 
JSONArray menuitemArr = popupObject.getJSONArray("menuitem");  
 
// lets loop through the JSONArray and get all the items 
for (int i = 0; i < menuitemArr.length(); i++) { 
    // printing the values to the logcat 
    Log.v(menuitemArr.getJSONObject(i).getString("value").toString()); 
    Log.v(menuitemArr.getJSONObject(i).getString("onclick").toString()); 
} 

Friday, December 07, 2012

Android: Enable and Disable WiFi Programmatically

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);

Internet Connection Check in Android


ConnectivityManager mgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if (netInfo != null) {
      if (netInfo.isConnected()) {
              // do something
      } else {
            AlertDialog.Builder alertbuilder = new AlertDialog.Builder(MyActivity.this);
            alertbuilder.setTitle("Internet");
            alertbuilder.setMessage("Internet is not available");
            alertbuilder.setNeutralButton("Ok", okClickListener);
           alertbuilder.show();
     }
} else {
      AlertDialog.Builder alertbuilder = new AlertDialog.Builder(
      MyActivity.this);
      alertbuilder.setTitle("Internet");
      alertbuilder.setMessage("Internet is not available");
      alertbuilder.setNeutralButton("Ok", okClickListener);
      alertbuilder.show();
}

SD Card Present in Android


public static boolean isSdCardPresent()
{
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}

Retrieve JSON from a REST web service in Android


String result = queryRESTurl("http://location/json.json");
try {
JSONObject json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++)
Log.i(TAG, "\n" + nameArray.getString(i) + "\n\n" + "\n" + valArray.getString(i) + "\n");
}   
catch (JSONException e) {       
Log.e("JSON", "There was an error parsing the JSON", e);
public String queryRESTurl(String url) {  
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);   
HttpResponse response;        
try {       
response = httpclient.execute(httpget); 
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]"); 
HttpEntity entity = response.getEntity();
if (entity != null) {  
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i(TAG, "Result of converstion: [" + result + "]"); 
instream.close();            
return result;       
}    
} catch (ClientProtocolException e) {  
Log.e("REST", "There was a protocol based error", e); 
} catch (IOException e) {   
Log.e("REST", "There was an IO Stream related error", e); 
}       
return null;
}

Thursday, December 06, 2012

Converting NSStrings to uppercase, lowercase and capitalizing each word in a string

NSString *str = @"easy tips for programming";
 
// Convert string to uppercase
NSString *upperStr = [str uppercaseStringWithLocale:[NSLocale currentLocale]];
NSLog(@"Upper Case: %@", upperStr);
 
// Convert string to caps
NSString *capStr = [upperStr capitalizedStringWithLocale:[NSLocale currentLocale]];
NSLog(@"Capital: %@", capStr);
 
// Convert string to lowercase
NSString *lowerStr = [capStr lowercaseStringWithLocale:[NSLocale currentLocale]];
NSLog(@"Lower Case: %@", lowerStr);
 
output:
Upper Case: EASY TIPS FOR PROGRAMMING
Capital: Easy Tips For Programming
lower Case: easy tips for programming
   
  

Thursday, August 30, 2012

Wednesday, August 01, 2012

Nil - NULL - NSNULL

There are 3 ways to represent a null value in Objective-C.

Nil            -> Absence of value with Objective-C object variables.
Null          -> Absence of value with C- style pointers.
NSNULL -> A nil boxed as an object for storage in a collection.

Wednesday, July 18, 2012

NSNumberFormatter remove the decimal point and trailing zeros


unsigned long int intToBeDisplayed = 1234567890;
NSNumber *longNumber = [NSNumber numberWithUnsignedLong:intToBeDisplayed];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setUsesGroupingSeparator:YES];
[formatter setGroupingSeparator:@","];
[formatter setGroupingSize:3];
[formatter setMaximumFractionDigits:0];
NSString *formattedNumber = [formatter stringFromNumber:longNumber];
NSLog(@"The formatted number is %@", formattedNumber);
Result : The formatted number is 1,234,567,890

Wednesday, June 20, 2012

How to Take ScreenShot and save in Photo Album

-(void)saveImageInPhotoAlbum{
    UIGraphicsBeginImageContext(
                              CGSizeMake(self.view.frame.size.width,
                                       self.view.frame.size.height));
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:context];
    UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSData *imageData = [NSData dataWithData:
                                UIImagePNGRepresentation(screenShot)];
    UIImage *image=[UIImage imageWithData:imageData];
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self 
          selector:@selector(saveImageInPhotoAlbum) 
    userInfo:nil repeats:NO];


// include QuartzCore Framework 
// #import <QuartzCore/QuartzCore.h>

Tuesday, June 19, 2012

Get Seconds from TimeFormat

code :

-(NSString *)getSeconds:(NSString *)timeString {
    NSArray *time    = [timeString componentsSeparatedByString: @":"];
    NSString *hours = [time objectAtIndex: 0];
    NSString *mins  = [time objectAtIndex: 1];
    NSString *secs  = [time objectAtIndex: 2];
    int total              = (([hours intValue] * 3600)+ ([mins intValue] * 60) + [secs intValue]);
    NSString* totalSeconds = [NSString stringWithFormat:@"%d", total];
    return totalSeconds;
}

usage: 


NSLog(@"Seconds : %@", [self getSeconds: @"01:30:48"]);

Friday, June 08, 2012

NSUserDefaults

Save :

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"stringKey"];


// saving an NSInteger
[prefs setInteger:100 forKey:@"integerKey"];


// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];



Retrieve :

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


// getting an NSString
NSString *myString = [prefs stringForKey:@"
stringKey"];


// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"
integerKey"];

// getting an Float
float myFloat = [prefs floatForKey:@"
floatKey"];

Reading data from .plist file

    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [bundlePath stringByAppendingPathComponent:@"Info.plist"];
    NSDictionary *plistData = [[NSDictionary dictionaryWithContentsOfFile:filePath] retain];
   
    versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,100,60,25)];
    versionLabel.backgroundColor = [UIColor clearColor];
    versionLabel.textColor = [UIColor whiteColor];
    versionLabel.font = [UIFont systemFontOfSize:10];
    NSString *versionString = [NSString stringWithFormat:@"v%@", [plistData objectForKey:@"CFBundleVersion"]];
    versionLabel.text = versionString;
    [self.view addSubview:versionLabel];

or simply :

NSString *s = [NSString stringWithFormat:@"App Version %@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
    versionLabel.text = s;

Wednesday, June 06, 2012

Prevent The iPhone From Sleeping

The code below will prevent the iPhone from dimming its screen and ultimately going to sleep.

[UIApplication sharedApplication].idleTimerDisabled = YES;

Monday, June 04, 2012

String matching and comparison

NSString* str1 = @"hello";
NSString* str2 = @"hello world";
NSRange matching = [str2 rangeOfString : str1];

// Searching for a string within another string
if(matching.location == NSNotFound){
    // str1 not found in str2
} else {
    // str1 found in str2
}

// Checking for equality
if([str1 isEqualToString:@"hello"]){
    // str1 is equal to "hello"
} else {
    // str1 is not equal to "hello"
}

Play a video in full screen

1. Include MediaPlayer framework in the project
2. Import header file in the view controller
3. Declare the player instance in the controller header file:
MPMoviePlayerViewController *playerViewController;

Sample Code : 
----------------
- (void) playVideo:(NSString *)fileName
{
    NSString *url = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(movieFinishedCallback:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:[playerViewController moviePlayer]];
    [self.view addSubview:playerViewController.view];
   
    //play movie
    MPMoviePlayerController *player = [playerViewController moviePlayer];
    [player play];        
}

// The call back
- (void) movieFinishedCallback:(NSNotification*) aNotification
{
    MPMoviePlayerController *player = [aNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:player];
    player.initialPlaybackTime = -1;
    [player stop];
    [player.view removeFromSuperview];   
    [player release];   
}

Scaling an image in iOS

The UIImage class can be used to represent an image. The following snippet scales an image according to a size which is provided with a CGSize parameter.

+ (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

Tuesday, May 29, 2012

How to Create ,Rename and Delete a file from Documents Directory

Documents Directory

// For error information
NSError *error;
 
// Create file manager
NSFileManager *fileMgr = [NSFileManager defaultManager];
 
// Document directory
NSString *documentsDirectory = [NSHomeDirectory() 
         stringByAppendingPathComponent:@"Documents"];
 
 
 
Creating a File
// File we want to create in the documents directory 
// Result is: /Documents/file1.txt
NSString *filePath = [documentsDirectory 
         stringByAppendingPathComponent:@"file1.txt"];
 
// String to write
NSString *str = @"Maheswaran.cm";
 
// Write the file
[str writeToFile:filePath atomically:YES 
         encoding:NSUTF8StringEncoding error:&error];
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",[fileMgr contentsOfDirectoryAtPath:
                           documentsDirectory error:&error]);
 
Renaming a File
 
// Rename the file, by moving the file
NSString *filePath2 = [documentsDirectory 
             stringByAppendingPathComponent:@"file2.txt"];
 
// Attempt the move
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 
                                              error:&error] != YES)
  NSLog(@"Unable to move file: %@", [error localizedDescription]);
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",[fileMgr contentsOfDirectoryAtPath:
                        documentsDirectory error:&error]);
 
Deleting a File
 
// Attempt to delete the file at filePath2
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
  NSLog(@"Unable to delete file: %@", [error localizedDescription]);
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",[fileMgr contentsOfDirectoryAtPath:
                                   documentsDirectory error:&error]); 

Wednesday, May 16, 2012

How to get Suck Effect in iOS

[UIView beginAnimations:@"suck" context:NULL];
[UIView setAnimationTransition:103 
                 forView:myViewContainer cache:YES];
[UIView setAnimationPosition:CGPointMake(12, 345)];
[myView removeFromSuperview];
[UIView commitAnimations]; 
 

 /*setAnimationTransition:103, it invokes suck effect.*/

For reference:
http://www.iphonedevwiki.net/index.php?title=UIViewAnimationState

Wednesday, April 04, 2012

How to Create a Universally Unique Identifier (UUID)

- (NSString *)CreateUUID
{
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    NSString *uuid = [NSString stringWithString:(NSString *)uuidStringRef];
    CFRelease(uuidStringRef);
    return uuid;
}

How to remind users to Restart App

-(void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease];
   
    // Current date
    NSDate *date = [NSDate date];
   
    // Add interval to the current time
    NSDate *dateToOpen = [date dateByAddingTimeInterval:timeInterval];
   
    // Set the fire date/time
    [localNotification setFireDate:dateToOpen];
    [localNotification setTimeZone:[NSTimeZone defaultTimeZone]];   
   
    // Setup alert notification
    [localNotification setAlertBody:@"Tap to return to MyApp" ];
    [localNotification setAlertAction:@"Open MyApp"];
    [localNotification setHasAction:YES];
   
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

How to Parse an NSURL Object in iOS

NSURL *url = [NSURL URLWithString:
 @"http://maheswarancm.com:999/2012/April;URLParsing?
                    url=testURL&purpose=testing"];
 
NSLog(@"URL Scheme: %@", [url scheme]); 
NSLog(@"URL Host: %@", [url host]); 
NSLog(@"URL Port: %@", [url port]);     
NSLog(@"URL Path: %@", [url path]);     
NSLog(@"URL Relative path: %@", [url relativePath]);
NSLog(@"URL Path components as array: %@", [url pathComponents]);        
NSLog(@"URL Parameter string: %@", [url parameterString]);   
NSLog(@"URL Query: %@", [url query]);       
NSLog(@"URL Fragment: %@", [url fragment]);
 
output:
URL Scheme: http
URL Host: maheswarancm.com
URL Port: 999
URL Path: /2012/April
URL Relative path: /2012/April
URL Path components as array: (
    "/",
    2012,
    April
)
URL Parameter string: URLParsing
URL Query: url=testURL&purpose=testing
URL Fragment: (null) 

Proximity Sensor use in iPhone

// Enabled monitoring of the sensor
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
 
// Set up an observer for proximity changes
[[NSNotificationCenter defaultCenter] addObserver:self
                selector:@selector(sensorStateMonitor:) 
         name:@"UIDeviceProximityStateDidChangeNotification" 
                object:nil];
 
- (void)sensorStateMonitor:(NSNotificationCenter *)notification
{
  if ([[UIDevice currentDevice] proximityState] == YES)
    NSLog(@"Device is close to user.");
  else 
    NSLog(@"Device is not closer to user.");
}
 

How to convert Radians to Degrees and Degrees to Radians in Objective c

Radians to Degrees
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
 
...
 
NSLog(@"Output radians as degrees: %f", RADIANS_TO_DEGREES(0.584));
 
 
Degrees to Radians
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
 
...
 
NSLog(@"Output degrees as radians: %f", DEGREES_TO_RADIANS(60));
 
 
 

How to get Mobile Network Code (MNC) and Mobile Country Code (MCC) in iOS

#import < CoreTelephony/CTCarrier.h >
#import < CoreTelephony/CTTelephonyNetworkInfo.h >
 
// Setup the Network Info and create a CTCarrier object
CTTelephonyNetworkInfo *networkInfo = [[ 
                                     [CTTelephonyNetworkInfo alloc]
                                                init] autorelease];
CTCarrier *carrier = [networkInfo 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);
 
// Get mobile network code
NSString *mnc = [carrier mobileNetworkCode];
if (mnc != nil)
  NSLog(@"Mobile Network Code (MNC): %@", mnc);
 
NSString *iso = [carrier isoCountryCode];
if (iso != nil) 
NSLog(@"ISO country Code (ISO): %@", iso);

Friday, January 20, 2012

Difference between a view’s bounds and frame

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.
The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

So, imagine a view that has a size of 100x100 (width x height) positioned at 50,50 (x,y) of its superview. The following code prints out this view's bounds and frame:
    NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
    NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
    NSLog(@"bounds.size.width: %f", label.bounds.size.width);
    NSLog(@"bounds.size.height: %f", label.bounds.size.height);

    NSLog(@"frame.origin.x: %f", label.frame.origin.x);
    NSLog(@"frame.origin.y: %f", label.frame.origin.y);
    NSLog(@"frame.size.width: %f", label.frame.size.width);
    NSLog(@"frame.size.height: %f", label.frame.size.height);
 
output: 
bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 100
bounds.size.height: 100

frame.origin.x: 25
frame.origin.y: 25
frame.size.width: 100
frame.size.height: 100

Monday, January 09, 2012

iOS versions and their mountain code names

  • 1.0: Alpine
  • 1.1: Little Bear
  • 2.0: Big Bear
  • 2.1: Sugarbowl
  • 2.2: Timberline
  • 3.0: Kirkwood
  • 3.1: Northstar
  • 3.2: Wildcat
  • 4.0: Apex
  • 4.1: Baker
  • 4.2: Jasper
  • 4.3: Durango
  • 5.0: Telluride
  • 5.1: Hoodoo

Tuesday, January 03, 2012

iOS: Adding Contacts Using AddressBook Framework

    ABRecordRef aRecord = ABPersonCreate();
   
    CFErrorRef  anError = NULL;
   
    ABRecordSetValue(aRecord, kABPersonFirstNameProperty,
                      CFSTR("MAHES"), &anError);
    ABRecordSetValue(aRecord, kABPersonLastNameProperty,
                     CFSTR("CHELLAIAH"), &anError);
    ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multiPhone, CFSTR("9751050790"), kABPersonPhoneMobileLabel, NULL); 
    ABRecordSetValue(aRecord, kABPersonPhoneProperty, multiPhone,nil);
    CFRelease(multiPhone);
   
    if (anError != NULL) {
       
        NSLog(@"error while creating..");
    }
   
    CFStringRef firstName, lastName;
    firstName = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty);
    lastName  = ABRecordCopyValue(aRecord, kABPersonLastNameProperty);
   
   
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreate(); 
   
    BOOL isAdded = ABAddressBookAddRecord (
                                           addressBook,
                                           aRecord,
                                           &error
                                           );
   
    if(isAdded){
       
        NSLog(@"added..");
    }
    if (error != NULL) {
        NSLog(@"ABAddressBookAddRecord %@", error);
    }
    error = NULL;
   
    BOOL isSaved = ABAddressBookSave (
                                      addressBook,
                                      &error
                                      );
   
    if(isSaved){
       
        NSLog(@"saved..");
        [self handleCall];
    }
   
    if (error != NULL) {
        NSLog(@"ABAddressBookSave %@", error);
    }
   
    CFRelease(aRecord);
    CFRelease(firstName);
    CFRelease(lastName);
    CFRelease(addressBook);

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...