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