Friday, November 1, 2013

encode URL ---- IOS


-(NSString *)encodeURL:(NSString *)urlString
{
    CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULLCFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
    return (NSString *)CFBridgingRelease(newString);
}

Monday, October 21, 2013

Scroll UITextView to top .--- IOS

 UITextView *YourTextView
  [YourTextView setContentOffset:CGPointMake(0, 0) animated:YES];

Sunday, October 6, 2013

Change TextView font , color etc using HTML -- IOS

NSString *htmlString = @"<html>Lorem  ipsum dolor sit er elit lamet,  <font face=\"verdana\">This is some text!</font>  consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.<h1> Excepteur sint occaecat cupidatat non proident,</h1> sunt in culpa qui <font size=\"2\" color=\"blue\"><b>This is some text!</b></font> officia deserunt mollit anim id est laborum. <b>Nam liber te conscient to factor tum poen legum odioque civiuda</b>ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu <b>fugiat nulla pariatur</b>. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda\n\n Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. <h2>Duis aute irure dolor in reprehenderit</h2> in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa <h3>qui officia</h3> deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda</html>";
   
   
    [YOURTEXTVIEW  setValue:htmlString forKey:@"contentToHTMLString"];


                                        ******************OR****************

1- Create a textfile and add in your project .. dummytext.txt
2- Put all HTML code in that file .


    NSString *htmlString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dummytext" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];


[YOURTEXTVIEW setValue:htmlString forKey:@"contentToHTMLString"];

This Load text from your textfile

check if an NSString contains 4 consecutive numbers --- IOS


- (BOOL)isSequence:(NSString *)string
{
    
    NSArray *arr = [NSArray arrayWithObjects:@"1234",@"2345",@"3456",@"4567",@"5678",@"6789"nil];
    
    BOOL found=NO;
    for (NSString *s in arr)
    {
        if ([string rangeOfString:s].location != NSNotFound) {
            NSLog(@"found");
            found = YES;
            break;
        }
    }

Thursday, September 26, 2013

Play Video from remote URL in UIWebView and MPMoviePlayerViewController ----- IOS

/***************************playVideoInWebView Start********************/
- (void)playVideoInWebView
{
 NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"YOUR----URL--HERE \" type=\"application/x-shockwave-mp4\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";
  
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height)];
  
    [self.webView setOpaque:NO];

    NSString *html = [NSString stringWithFormat:embedHTML, self.webView.frame.size.width, self.webView.frame.size.height];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUR_URL_HERE"]]];

    [self.webView scalesPageToFit];

    webView.delegate = self;
  
    [self.view addSubview:webView];
 

}

/***************************playVideoInWebView End********************/



/***************************playVideoInMoviePlayer Start********************/

- (void)playVideoInPlayer
{
   moviePlayerController_ = [[MPMoviePlayerViewController alloc] init];
     url = [NSURL URLWithString:@"https://testvideo.fidelity.tv/asset/l6yo1b8uYfv.mp4?format=mobile_mp4"]; 
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlaybackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:nil];
   
    self.moviePlayerController_.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
    [self.moviePlayerController_.moviePlayer setContentURL:url];
    [self presentMoviePlayerViewControllerAnimated:self.moviePlayerController_];
   
}


- (void)moviePlaybackDidFinish:(NSNotification*)noti{

    NSLog(@"finish..%@",[noti userInfo]);
 
}

/***************************playVideoInMoviePlayer End********************/

stop deletion of complete text in case of secure Textfield on backspace.--- IOS

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   
    // backspace functionality
    if (range.location > 0 && range.length == 1 && string.length == 0)
    {
        UITextPosition *beginning = textField.beginningOfDocument;
        UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
        NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length;
        NSString *text = textField.text;

        // Trigger deletion
        [textField deleteBackward];

        if (textField.text.length != text.length - 1)
        {
            textField.text = [text stringByReplacingCharactersInRange:range withString:string];
            UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset];
            UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
            [textField setSelectedTextRange:newSelectedRange];
        }
        return NO;
    }   
       
    return YES;
}

Wednesday, September 25, 2013

How to stop --- if space is pressed twice, a full-stop gets appeared automatically --- IOS

Replace " . " with space ----- if space is pressed twice, a full-stop gets appeared automatically ---- IOS



if ( (range.location > 0 && [string length] > 0 &&
          [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[string characterAtIndex:0]] &&
          [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textField text] characterAtIndex:range.location - 1]]) )
    {
        //Manually replace the space with your own space, programmatically
        textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@" "];

        //Tell Cocoa not to insert its space, because you've just inserted your own
        return NO;
    }



//User not enter after 1st space in UITextField --- ios

return !(range.location > 0 &&
             [string length] > 0 &&
             [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[string characterAtIndex:0]] &&
             [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textField text] characterAtIndex:range.location - 1]]);

Tuesday, September 24, 2013

Check if a UITextField has blank spaces entered --- ios

NSString *rawString = [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
    // Text was empty or only whitespace.
}

Monday, September 23, 2013

easy way to dismiss keyboard if it is on screen --- ios

- (void)resignKeyBoard{

    [self.view endEditing:YES];
   

}

DEtect if Keyboard is present on screen or not ....-- IOS

- (void) isKeyboardOnScreen
{
    BOOL isKeyboardShown = NO;
   
    NSArray *windows = [UIApplication sharedApplication].windows;
    if (windows.count > 1) {
        NSArray *wSubviews =  [windows[1]  subviews];
        NSLog(@"wSubviews..%@",wSubviews);
        isKeyboardShown = YES;
      
       

    }
   
     NSLog(@"isKeyboardShown...%d",isKeyboardShown);
}

Tuesday, September 17, 2013

Capitalise first letter in String --- ios

- (NSString*)capitaliseFirstLetterInString:(NSString*)textString{
    NSString *text = textString;
    NSString *capitalizedString = [[[text substringToIndex:1] uppercaseString] stringByAppendingString:[text substringFromIndex:1]];
   
    NSLog(@"%@ uppercased is %@", text, capitalizedString);
    return capitalizedString;
}

Tuesday, September 10, 2013

Get first two Character of String --- IOS

NSString *getString =[String substringToIndex:2];

UITextfield Input to Upper Case forcefully -- ios sdk


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {

    // Check if the added string contains lowercase characters.
    // If so, those characters are replaced by uppercase characters.
    // But this has the effect of losing the editing point
    // (only when trying to edit with lowercase characters),
    // because the text of the UITextField is modified.
    // That is why we only replace the text when this is really needed.
    NSRange lowercaseCharRange;
    lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

    if (lowercaseCharRange.location != NSNotFound) {

        textField.text = [textField.text stringByReplacingCharactersInRange:range
                                                                 withString:[string uppercaseString]];
        return NO;
    }

    return YES;
}

Number of Occurrences of a Character in NSString -- ios sdk

NSString *firstString = @"vijayadhikari"
NSScanner *scanner = [NSScanner scannerWithString: firstString];

NSCharacterSet *countChar = @"a"
NSString *charactersFromString;

if (!([scanner scanCharactersFromSet:countChar intoString:&charactersFromString])) {
    NSLog(@"characters not  found");
}

NSInteger characterCount = [charactersFromString length]; 

// should return 3 for this example

check if a string is numeric or not --- IOS SDK


NSScanner *scanner = [NSScanner scannerWithString:testString];
BOOL isNumeric = [scanner scanInteger:NULL] && [scanner isAtEnd];

remove common letters in two Strings ---- iOS SDK

NSString *combined = [string1 stringByAppendingString:string2];



NSMutableString *result = [combined mutableCopy];
NSMutableSet *chars = [NSMutableSet set];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
               options:NSStringEnumerationByComposedCharacterSequences
            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                if ([chars containsObject:substring]) {
                    [result deleteCharactersInRange:substringRange];
                } else {
                    [chars addObject:substring];
                }

            }];

check that a string is numeric only with limit in UITextField.----- IOS

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    /* for backspace */
    if([string length]==0){
        return YES;
    }
   
    /*  limit to only numeric characters  */
   
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if ([myCharSet characterIsMember:c]) {
            NSUInteger newLength = [textField.text length] + [string length] - range.length;
            return (newLength > 8 ) ? NO : YES;

        }
    }
   
    return NO;
}

Monday, September 9, 2013

validate Email Using Regex-- ios sdk



-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = YES; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
   NSString *laxString = @".+@([A-Za-z0-9]+\\.)+[A-Za-z]{2}[A-Za-z]*";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Set Char Input Limit to UITextfield in iPhone -- IOS SDK

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
  
NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 30) ? NO : YES;

}

Sunday, September 8, 2013

UK Postal code Validation using regex -- iOS



- (BOOL) validateUKPostalCode: (NSString *) code {
  

    NSString *ukcodeRegex = @"(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})";
    NSPredicate *codeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ukcodeRegex];
    
    return [codeTest evaluateWithObject: code];
}

Wednesday, September 4, 2013

Google Analytics Integration in ios ---- IOS SDK

Google Analytics, Create a new profile
You can download it from: http://code.google.com/apis/analytics/docs/tracking/mobileAppsTracking.html.

Step 1: Add a new websites profile.

Step 2: Select Add a Profile for a new domain.
Step 3: Enter URL (no need to be a live URL, e.g.: testapp.articledean.com). Google never uses this URL; this entry is just for our reference, so a meaningful URL will do.
Step 4: Select the Country and TimeZone.
Step 5: Click Finish, and Google Analytics will give you a Web Property ID that starts with UA. Note it down; this is the unique identification of your application. This ID looks like: Web Property ID: UA-12345678-2 (Sample ID).

Download and Integrate the Google Analytics Library for iPhone Applications
Download link: Analytics SDK for iPhone.
Download and extract the library. The following two files are the key components of the Google Analytics Library.
    1.    GANTracker.h
    2.    libGoogleAnalytics.a
Copy the above files into the library folder of you iPhone application in XCode. Make sure that you are copying the files into the destination folder.

Google Analytics Library requires "CFNetwork" and "libsqlite3.0.dylib
Using the Google Analytics Library in code
Import the "GANTracker.h" file into your application delegate class. In the "applicationDidFinishLaunching()" method, initialize the tracker object.
#import "GANTracker.h"
[[GANTracker sharedTracker] startTrackerWithAccountID:@"UA-12345678-2"
                               dispatchPeriod:20
                               delegate:nil];
Google Analytics supports two levels of tracking: "PageViews" and "Events". "Page Views" are like tracking regular web pages."Events" tracking can be used on button clicks, radio button selections, text box entries etc.

Page Views sample code in the applicationDidFinishLaunching method
NSError *error;
if (![[GANTracker sTracker] trackPageview:@"/applicationlaunched"
                                        withError:&err]) {
     // Error Handling
   }
Events sample code, when an event fires (like button click)
- (IBAction) clickMe:(id) sender
{
        NSError *err;
        if (![[GANTracker sTracker] trackEvent:@"clkButton"
                                            action:@"trackMyPage"
                                            label:@"sampleLabel"
                                            value:-1
                                        withError:&err]) {
               // Error Handling

        }
}
    •    "clkButton" is a group that represents a Button Click Event category. You can track all your button clicks by using this user defined group.
    •    "trackMyPage" is the event name when my button is clicked; I will call the "trackMyPage" event method.
    •    "sampleLabel" is just a label that gives you information about your tracking.

Get count of row Selected in UITableView -- IOS

Create NSmutalble Array in your .h file -
NSMutableArray *SelectedRowCountArr;

in .m File :-
- (void)viewDidLoad
{
       SelectedRowCountArr = [[NSMutableArray alloc]init];
   }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 if(![SelectedRowCountArr containsObject:indexPath])
    {
        [SelectedRowCountArr addObject:indexPath];

    }else{
    [SelectedRowCountArr removeObject:indexPath];

    }

    NSLog(@"SelectedRowCountArr.count...%d",SelectedRowCountArr.count);
}

Tuesday, September 3, 2013

Saving Data in the keychain ---- iphone sdk


 Keychain to store usernames and passwords, and since it's stored securely and only accessible to your app
Download Sample code from Apple website sample code 
Add Security.framework 
Add KeychainItemWrapper .h & .m files into your project
 #import the .h file wherever you need to use keychain and then create an instance of this class:
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"AppLoginItems" accessGroup:nil];
(AppLoginItems can be anything you choose to call your Keychain item and you can have multiple items if required)
Then you can set the username and password using:
[keychainItem setObject:@"password you are saving" forKey:kSecValueData];
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

Get them using:
NSString *password = [keychainItem objectForKey:kSecValueData];
NSString *username = [keychainItem objectForKey:kSecAttrAccount];

Or delete them using:
[keychainItem resetKeychainItem];

Friday, July 19, 2013

Change UITextField placeholder text color -- iPhone

The introduction of attributed strings in UIViews in iOS 6, it's possible to assign a color to the placeholder text like this:
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

Sunday, July 14, 2013

capitalize first letter of NSString IOS - iPhone


NSString *myString = @"i love iPhone";
NSString *newString = [myString stringByReplacingCharactersInRange:NSMakeRange(0,1withString:[[myStringsubstringToIndex:1capitalizedString]];

Result -  "I love iPhone"

Facebook/Twitter API Integration in iOS6 - iPhone

You need to add Social.framework in your project.
Add  ---  #import "Social/Social.h"

You can create 3 type of service:


SLServiceTypeTwitter;
SLServiceTypeFacebook;
SLServiceTypeSinaWeibo;


For Facebook -

SLComposeViewController *facebookController=[SLComposeViewControllercomposeViewControllerForServiceType:SLServiceTypeFacebook];


if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
        SLComposeViewControllerCompletionHandler __block completionHandler=^(SLComposeViewControllerResultresult){
        
        [facebookController dismissViewControllerAnimated:YES completion:nil];
        
        switch(result){
        case SLComposeViewControllerResultCancelled:
        default:
        {
            NSLog(@"Result Cancelled");
            
        }
            break;
        case SLComposeViewControllerResultDone:
        {
            NSLog(@"Result Post Done");
        }
            break;
    }};
    
    [facebookController addImage:[UIImage imageNamed:@"yourImage.jpg"]];
    [facebookController setInitialText:@"Check out this cool IOS Blog"];
    [facebookController addURL:[NSURL URLWithString:@"http://vijaysinghadhikari.blogspot.in/"]];
    [facebookController setCompletionHandler:completionHandler];
    [self presentViewController: facebookController animated:YES completion:nil];
}

Wednesday, July 10, 2013

Disable Cut,Copy, Select, Select All in UITextView - IOS


 Create a subclass of UITextView that overrides the canPerformAction:withSender: method to return NO for actions that you don't want to allow:
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:))
        return NO;
    return [super canPerformAction:action withSender:sender];
}

Tuesday, July 9, 2013

Twitter Integration in IOS 5 using Twitter Framework +iPone



1 :- Add Twitter.framework
2 :- open ViewController.m and add the following import at the top of the file:
#import <Twitter/Twitter.h>

- (IBAction)twitterButtonClicked:(id)sender {
    {
        if ([TWTweetComposeViewController canSendTweet])
        {
            TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc] init];
            [tweetSheet setInitialText:
             @"Your tweet Message"];
            [self presentModalViewController:tweetSheet animated:YES];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc]
                                      initWithTitle:@"Notification"
                                      message:@"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup"
                                      delegate:self
                                      cancelButtonTitle:@"OK"                                                   
                                      otherButtonTitles:nil];
            [alertView show];
        }
    }
}

GData Integration in iphone


Step 1
The first step, is to head on over to the Google Code website for the Objective-C Client, download and extract the zip file source code. Alternatively, you can get the latest and greatest version via Subversion using:
svn checkout http://gdata-objectivec-client.googlecode.com/svn/trunk/ gdata-objectivec-client-read-only
If you downloaded the zip file from the website, you’ll have version 1.7.0, and if you used the svn code you’ll have a -read-only folder.
Step 2
Open up the GData XCode Project from your downloaded folder as well as your iPhone App XCode project.
Step 3
Drag over the GData Sources Folder from the GData project to your iPhone App project and add it as reference [don't check the box for Copy items into destination group's folder (if needed).] You do not need to copy over all the files into your project. You can, but it’s not required.
Step 4
Open up the build settings for your iPhone App project. Located and set the following settings. * Header Search Paths: /usr/include/libxml2 ../gdata-objectivec-client-1.9.1/Source * Other Linker Flags: -lxml2, -ObjC
For the Debug build configuration only, add the Other C Flags setting so that the library’s debug-only code is included:
Other C Flags: -DDEBUG=1
Step 5
Now be sure that the downloaded source code is in the same directory in which your actual Code Folder is.
Step 6 Make sure I've the frameworks "SystemConfiguration.FrameWork" and "Security.FrameWork" added to your project.
.These are the steps for GData integration

Check dis Link 4 more help ;-
http://hoishing.wordpress.com/2011/08/23/gdata-objective-c-client-setup-in-xcode-4/

Monday, July 8, 2013

App executing tasks in background +iPhone


-(void) applicationDidEnterBackground:(UIApplication*)application {
    
    UIApplication *app = [UIApplication sharedApplication];
    UIBackgroundTaskIdentifier bgTask = 0;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
}

Wednesday, June 5, 2013

disable UIAlert View Button-- iOS


//##########################################################
#pragma mark - Action Sheet Delegate
//########################################################## //vijay
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    for (UIView* view in [actionSheet subviews])
    {
      
        NSLog(@"[[view class] description]..%@",[[view class] description]);

        if ([[[view class] description] isEqualToString:@"UIAlertButton"])
        {
            if ([view respondsToSelector:@selector(title)])
            {
                NSString* title = [view performSelector:@selector(title)];
                if ([title isEqualToString:@"UIAlert View Title"] && [view respondsToSelector:@selector(setEnabled:)])
                {
                    if (hideTranscription) {
                         [view performSelector:@selector(setEnabled:) withObject:NO];
                    }
                   
                }      
            }       
        }  
    }
}

Thursday, May 2, 2013

Globally change navigation bar title color using appearance - IOS

//For Navigation BAR
  NSDictionary *text = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor GreenColor], UITextAttributeTextColor, [UIColor whiteColor], UITextAttributeTextShadowColor, nil];

    [[UINavigationBar appearance] setTitleTextAttributes:text];



//For Navigation Item


   [[UIBarButtonItem appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      [UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:1.0],
      UITextAttributeTextColor,
      [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0],
      UITextAttributeTextShadowColor,
      [NSValue valueWithUIOffset:UIOffsetMake(0, 1)],
      UITextAttributeTextShadowOffset,
      [UIFont fontWithName:@"Helvatica" size:0.0],
      UITextAttributeFont,
      nil]  forState:UIControlStateNormal];

Friday, April 26, 2013

change a sprite image in cocos2d iOS

CCTexture2D *firstImage = [[CCTextureCache sharedTextureCache] addImage:@"Image1.png"];

CCTexture2D *secondImage = [[CCTextureCache sharedTextureCache] addImage:@"Image2.png"];

CCSprite *sprite = [CCSprite spriteWithTexture: firstImage];


[self addChild:sprite];

 change the image of the sprite to secondImage:- 
sprite.texture = secondImage;

Tuesday, April 16, 2013

Determine device (iPhone,iPad , iPod Touch) with iPhone SDK


if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            NSLog(@"I'm iPad");
    } else {
    NSString *deviceType = [UIDevice currentDevice].model;
                if([deviceType rangeOfString:@"iPhone"].location!=NSNotFound)
                {
                    NSLog(@"I m iPhone");

                } else {
                    NSLog(@" I'm  iPod");

                }
}

Thursday, April 11, 2013

Point the user back to the Location Services screen in the Settings app


[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"prefs:root=LOCATION_SERVICES"]];

Sunday, April 7, 2013

Get Custom Album name Using ALAsset Library IOS ....


 __block ALAssetsGroup* groupToAddTo;
    [self.library enumerateGroupsWithTypes:ALAssetsGroupAlbum
                                usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                                     NSLog(@"[group valueForProperty:ALAssetsGroupPropertyName]  %@", [group valueForProperty:ALAssetsGroupPropertyName] );
                                    if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:albumName]) {
                                        NSLog(@"found album %@", albumName);
                                        groupToAddTo = group;
                                    }
                                }
                              failureBlock:^(NSError* error) {
                                  NSLog(@"failed to enumerate albums:\nError: %@", [error localizedDescription]);
                              }];

Friday, April 5, 2013

Save Image to document directory IOS:-


Save Image to document directory:-

- (void)saveImage {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
    NSLog(@"savedImagePath..%@",savedImagePath);
    NSData *imageData = UIImagePNGRepresentation(Image);
    [imageData writeToFile:savedImagePath atomically:YES];  
    
  
}

Get Original Image from Photolibrary using ALAsset IOS


Get Original Image from Photolibrary:-

 ALAssetRepresentation *rep = [[dataContainer objectAtIndex:indexPath+1] defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        UIImage *image = [UIImage imageWithCGImage:iref];
    }

Get images from photolibrary using ALAsset.... IOS


- (void)getImagesFromPhotoLibrary{ 
void (^assetsEnumeration)(ALAsset *,NSUInteger,BOOL *) = ^(ALAsset *asset,NSUInteger index,BOOL *stop){
        
        if(asset!=nil)
        {
            NSLog(@"obtained Asset %@",[asset valueForProperty:ALAssetPropertyURLs]);
            
            [self.dataContainer addObject:asset];
            NSLog(@"assest...%@",asset);
             [self setImage];
             
        }
       NSLog(@"data container...%@",self.dataContainer); 
    };
    
    void (^assetsGroupEnumeration)(ALAssetsGroup *,BOOL *) = ^(ALAssetsGroup *group,BOOL *status){
        
        if(group!=nil)
        {
            [group enumerateAssetsUsingBlock:assetsEnumeration];
        }
        
    };
    // allocate the library
    library = [[ALAssetsLibrary alloc]init];
    
    [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetsGroupEnumeration failureBlock:^(NSError *error) {
        NSLog(@"Error :%@", [error localizedDescription]);
    }];
}



Set Image:-
    [imageview.image setImage:[UIImage imageWithCGImage:[(ALAsset*)[dataContainer objectAtIndex:indexPath ]thumbnail]]];