Common method in Swift

1. Check for any field empty in NSDictionary

class func checkforEmptyValueinDictioanty(dic:NSDictionary)-> Bool{

for (keyVal, dataVal) in dic {

  if (dataVal.length()==0){

                println(\(keyVal): \(dataVal.length()))

                return false




        return true


2.Email validation

class func isValidEmail(testStr:String) -> Bool {

let fullNameArr = testStr.componentsSeparatedByString(“@”)

        var firstPart: String = fullNameArr[0]

        if let range = firstPart.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()){


            return false


      let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”

 var emailTest = NSPredicate(format:“SELF MATCHES %@”, emailRegEx)

        let result = emailTest.evaluateWithObject(testStr)

        return result


3. Alert in Swift

class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {


        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)


            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)





4. NSUserDefaults in swift as common function

class func saveToUserDefault(value:AnyObject, key:String)


        NSUserDefaults.standardUserDefaults().setObject(value, forKey:key)




    class func userDefaultForKey(key:String) -> String


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as NSString



    class func userDefaultForAny(key:String) -> AnyObject


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as AnyObject!



    class func userdefaultForArray(key:String) -> Array<AnyObject>


        return NSUserDefaults.standardUserDefaults().objectForKey(key) as Array



    class func removeFromUserDefaultForKey(key:String)






5.Get screen height and width

let _screenWidth=UIScreen.mainScreen().bounds.size.width

let _screenHeight=UIScreen.mainScreen().bounds.size.height


Use HexColor in Swift as a color

Add it in your class 

extension UIColor {

   convenience init(red: Int, green: Int, blue: Int) {

       assert(red >= 0 && red <= 255, “Invalid red component”)

       assert(green >= 0 && green <= 255, “Invalid green component”)

       assert(blue >= 0 && blue <= 255, “Invalid blue component”)

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)


   convenience init(netHex:Int) {

       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)



Use it where you need…….

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)

var color2 = UIColor(netHex:0xFFFFFF)

Basic HTTP Authentication in iOS while calling webservice

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

    if ([challenge previousFailureCount] == 0) {

        NSLog(@”received authentication challenge”);

        NSURLCredential *newCredential = [NSURLCredentialcredentialWithUser:@”tylerhorne”



        NSLog(@”credential created”);

        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

        NSLog(@”responded to authentication challenge”);


    else {

        NSLog(@”previous authentication failure”);



Post Json data to server in iOS


NSString *url= SERVER_URL;

NSLog(@”url is %@”,url);


NSMutableURLRequest *_request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:url]




NSMutableDictionary *post=[[NSMutableDictionaryalloc] init];

[post setObject:_emailText.text forKey:@”username”];

[post setObject:_passText.text forKey:@”password”];


NSError *error;

NSData *data=[NSJSONSerializationdataWithJSONObject: post options:kNilOptionserror:&error];

NSString *jsonString = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

NSString *post = [NSString stringWithFormat:@”json=%@”, jsonString];

NSData*postData = [post dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:NO];


NSLog(@”string is %@”,post);

[_request setHTTPMethod:@”POST”];

[_request setValue:@”application/x-www-form-urlencoded”forHTTPHeaderField:@”content-type”];

[_request setHTTPBody:postData];


NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:_request delegate:self];

[connection start];





– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

if ([challenge previousFailureCount] == 0) {

NSLog(@”received authentication challenge”);

NSURLCredential *newCredential = [NSURLCredentialcredentialWithUser:@”tylerhorne”



NSLog(@”credential created”);

[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

NSLog(@”responded to authentication challenge”);


else {

NSLog(@”previous authentication failure”);





– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response





– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data


// Append the new data to receivedData.

// receivedData is an instance variable declared elsewhere.


NSDictionary *response=[NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

NSLog(@”response %@”,response);






– (void)connection:(NSURLConnection *)connection

didFailWithError:(NSError *)error



NSLog(@”Connection failed! Error – %@ %@”,

[error localizedDescription],

[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);


Move upward textField in Scrollview when keyboard appears

Step 1>>First add a view in Interface class

@property(weak, nonatomic) UIView *activeTextView;

Add Notification in ViewWillAppear

– (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    // register for keyboard notifications

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotificationobject:nil];

     [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillBeHidden:) name:UIKeyboardDidHideNotificationobject:nil];


Step 2>>

– (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];

    // unregister for keyboard notifications

    [[NSNotificationCenterdefaultCenter] removeObserver:selfname:UIKeyboardDidShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter] removeObserver:selfname:UIKeyboardDidHideNotificationobject:nil];


Step 3>>

– (void)textFieldDidBeginEditing:(UITextField *)textField{

    // save the text view that is being edited

 self.activeTextView = textField;


– (void)textFieldDidEndEditing:(UITextField *)textField{

    // release the selected text view as we don’t need it anymore

    self.activeTextView = nil;


Step 4>>

– (void)keyboardWasShown:(NSNotification *)aNotification


 NSDictionary* info = [aNotification userInfo];

    CGSize kbSize= [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect bkgndRect = activeTextView.superview.frame;

    bkgndRect.size.height += 200;//kbSize.height;

    [activeTextView.superview setFrame:bkgndRect];

    [_scrollViewsetContentOffset:CGPointMake(0.0, activeTextView.frame.origin.y200) animated:YES];



// Called when the UIKeyboardWillHideNotification is received

– (void)keyboardWillBeHidden:(NSNotification *)aNotification


    // scroll back..

   /* UIEdgeInsets contentInsets = UIEdgeInsetsZero;

    _scrollView.contentInset = contentInsets;

    _scrollView.scrollIndicatorInsets = contentInsets;*/

    [self._scrollViewsetFrame:CGRectMake(0, 0, self._scrollView.frame.size.width, self._scrollView.frame.size.height)];


Call a function using Notification in Xcode

Step 1: Post Notification from class A.

NSString *data=@”Demo”;[[NSNotificationCenter defaultCenter] postNotificationName:@”golferUpdate” object:nil userInfo:data];if you do not want to pass data use 

[[NSNotificationCenter defaultCenter] postNotificationName:@golferUpdate object:nil];

Step 2: Register Notification in Class B.

[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(GetData:) name:@”golferUpdate”object:nil];

Step 3: Add function GetData

-(void)GetData:(NSNotification *)notification{

    NSDictionary *dict = [notification userInfo];

// write your code Here




Step 4: Enjoy Coding………..

Best Of Luck.

Send Class Name as a argument in iOS

Step 1::   in your current class.

#import “HomeView.h”

#import “MSYCommon.h”

Step 2 ::

*call this from any method of view where MSYCommon is a name of common class.

[MSYCommon pushBackToSpecific:self.navigationController withName:@”HomeView”];

Step 3″:: in MSYCommon class

+(void)pushBackToSpecific:(UINavigationController *)nav withName:(NSString *)screenName{

    Class classFromString = NSClassFromString(screenName);

    for (UIViewController *controller in nav.viewControllers) {

        if ([controller isKindOfClass:[classFromString class]]) {

             [nav popToViewController:controller animated:YES];






You Will able to go back to any specific class.

Note:: You can also convert A Class to variable like this

MyClass * variable = [factory makeObjectOfClass:[MyClass class]];

Best Of Luck

Pop to specific View controller in iOS

First Method ::

- (void) RetunToSpecificViewController{

    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[AnOldViewController class]]) { 
        //Do not forget to import AnOldViewController.h

            [self.navigationController popToViewController:controller

Second Method ::

NSArray *array = [self.navigationController viewControllers];

[self.navigationController popToViewController:[array objectAtIndex:2] animated:YES];
Best Of Luck.

Live Video Face Masking on iOS

A great post to live video processing

Chris Cavanagh's Blog

Face detection has been possible for some time on iOS thanks to libraries like OpenCV. The CIDetector class introduced in iOS 5 made it a standard feature. Since iOS 7 it can also detect smiles and eye blinks Smile

With iOS 6, AV Foundation gained AVCaptureMetadataOutput, allowing face detection to be included in the capture pipeline (in iOS 7 it also supports barcode scanning).

Here’s how you could use that to perform face masking on live video:


First thing to do is get the capture session set up:

 AVCaptureSession *captureSession = [AVCaptureSession new]; [captureSession beginConfiguration]; NSError *error; // Input device AVCaptureDevice *captureDevice = [self frontOrDefaultCamera]; AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error]; if ( [captureSession canAddInput:deviceInput] ) { [captureSession addInput:deviceInput]; } if ( [captureSession canSetSessionPreset:AVCaptureSessionPresetHigh] ) { captureSession.sessionPreset = AVCaptureSessionPresetHigh; } // Video data output AVCaptureVideoDataOutput *videoDataOutput = [self createVideoDataOutput]; if ( [captureSession canAddOutput:videoDataOutput] ) { [captureSession addOutput:videoDataOutput]; AVCaptureConnection *connection…

View original post 511 more words

Make a Very fast Android emolator

Testing on multiple mobile devices is costly, time consuming and the default Android emulator is notoriously slow. So, what should we do? That’s easy – start using a properly fast Android emulator.
When developing Android applications, you have to keep in mind all the different Android OS versions and various screen sizes and resolutions. The main objective before releasing an application is to find bugs and design imperfections.

Default Android emulator
The great thing about using an emulator for development is that it gives you an opportunity to develop applications without having a real Android device. The default Android emulator comes together with the Android SDK and can be found in the “tools” folder.

So far so good, we have our cake, but can we eat it? The answer comes about 5 minutes after we hit the “Launch” button. Go grab a coffee. Have breakfast. Come back. Wait another 5 minutes. Maybe even more.

Finally – the emulator launches, only to show how slow it actually is.

Boot animation

All these performance problems stem from the fact that it emulates an ARM processor so it can run the actual code of your application. It accomplishes that by providing dynamic binary translation of the device machine code to the OS and processor architecture of your development machine.

Basically, it does a lot of mumbo-jumbo to pretend it’s an ARM processor – when actually it isn’t.


Well, first, we can help our CPU out by delegating the rendering process to the GPU by checking “Use Host GPU” checkbox in AVD’s edit window. The screen should now look better and be more responsive. That’s because the CPU is not dealing with the tedious work of doing rendering anymore. But, that’s still not fast enough.
Host GPU

We can download Intel Atom (x86) images and, while we’re at it, download Intel x86 Emulator Accelerator (HAXM, for Mac and Windows only). This will enable virtual machine acceleration capabilities of the Intel CPU (for more information check this link).
Now we’re getting somewhere, once this baby starts up, it should run fast and smooth.

x86 and HAXM

You could say that this level of speed should be sufficient. That may be true, but an issue with the Intel x86 images is that you don’t get Google Apps, they only come with ARM images. This is important if you’re testing an app that uses GMaps, or Google Play Services.

So, as we’ve seen, ARM images aren’t fast enough even with hardware acceleration. And emulators don’t have the Play Store. What now?

Genymotion by Genymobile
Genymotion is a new, fast Android emulator developed by the French company Genymobile. It’s based on the open-source project AndroVM, and the first beta version was released back in June.

It runs on all major platforms (Mac, Windows, Linux). For now it’s freely available, but there is also going to be a paid version.

According to AndroVM blog, the free version will be feature-rich, and the paid version will be intended for large companies needing a higher level of collaboration on Genymotion.


Genymotion relies on Oracle VirtualBox to work (version 4.1 or above). So…

Download and install VirtualBox. For Windows users it’s not necessary to install VirtualBox separately, because it is available from the Genymotion site, bundled with the Genymotion emulator.

Go to Genymotion website and sign up. You’ll receive a validation mail, so just click on the validation link to proceed.

Download and install the Genymotion emulator (the current version is 1.1.0).

Start Genymotion. You might need to configure path to your Android SDK location in Genymotion settings (probably if you’ve installed SDK in a non default location). Since this is a first start, there are no devices. Click on “Add” and download new device. To see available devices, write your credentials in the pop-up dialog and click “Connect”.

Select the device and click “Start”.

It starts quickly and is insanely fast! It’s a little awkward to start the emulator separately, but Genymotion provides Eclipse and Android Studio integration through plugins, also available on Genymotion website. To use the plugin, you have to provide a path to Genymotion installation and Android SDK, as well.

Eclipse plugin


Well, for me, the sheer speed of Genymotion is what got me using it in the first place. Which is kind of funny, because in the first version you couldn’t even rotate the device.

But, alongside the speed bump, it also provides GPS, compass and battery control via some good-looking widgets.


Battery control widget


The GPS widget even provides GMaps for selecting mock locations, which is really nice for testing location based apps.


Through the Genymotion shell it’s also possible to control the device’s angle (accelerometer), but it would be cool to control it using a widget, something like the Windows phone emulator does.


Genymotion devices with Google Apps also come with the Play Store preinstalled. This comes in handy if you want to test an app from the Play Store quickly.


Multiple screen sizes are one of Android developer’s worst nightmares. There is a huge number of different screen configurations of Android devices.

Android multiple screen sizes

Genymotion, as well as the default emulator, offers custom configuration of device’s screen. In the list of available devices, select the device for which you want to change screen configuration and click on the monitor icon on the right side. Then simply select one of the predefined screen resolutions or create your own.

Screen configuration

Final result

Be careful when choosing resolution, because you may end up with something rather strange…


The main setback of Genymotion is that it only provides devices with API version 16, 17 and a preview version of Android 4.3 (API 18). If we take a look at Google Dashboard, we’ll see that Gingerbread still holds about 33% of all devices (API 10).

So, for testing on that platform you still need either a default emulator or real device, which kind of defeats the purpose of Genymotion as a testing platform.

And there is no camera, which I don’t miss, but could be really useful.

In the future, we can expect even more features, like taking screenshots or video screen capturing (which would be great for making demonstration videos). An accelerometer widget would be cool, and even a camera would be nice, but we can only wait and see.

Final thoughts
Well, you can never really get rid of real devices, because you’ll always want to test an app on a real device before releasing it. But during development I recommend using a Genymotion emulator. Even though it doesn’t cover all major Android OS versions. It’s fast, stable, the GPS sensor manipulation is awesome and with the device rotation feature added to the 1.1.0 version – it’s truly the way to go.

Also, deploying apps is almost instant and that can save you a lot of time when you’re doing small changes to the app. But you have to watch out since the Genymotion emulator runs faster than real devices themselves, giving you a false impression of the performance of the app.

Always test on a real device!