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()){

 }else{

            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)

        }else{

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

            alert.show()

           

        }

    }

4. NSUserDefaults in swift as common function

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

    {

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

        NSUserDefaults.standardUserDefaults().synchronize()

    }

    

    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)

    {

        NSUserDefaults.standardUserDefaults().removeObjectForKey(key)

        NSUserDefaults.standardUserDefaults().synchronize()

        

    }

5.Get screen height and width

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

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

Advertisements

Use different font text in a Label in swift


let secondLabel=UILabel(frame: CGRectMake(0, 16, _screenWidth2, 20))

        secondLabel.textColor=UIColor.whiteColor()

        secondLabel.textAlignment=NSTextAlignment.Center

        secondLabel.font=UIFont(name: “Arial”, size: 12)

        bottomView.addSubview(secondLabel)

        

        let attrSting=NSMutableAttributedString(string: “I agree to the Terms of Service and Privacy Policy.”)

        

        NSLog(“text length is %d”, attrSting.length)

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(15, 16))

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica”, size: 12), range: NSMakeRange(31,4 ))

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(35, 15))

        

        secondLabel.attributedText=attrSting

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”

                                                                    password:@”m2n1shlko”

                                                                 persistence:NSURLCredentialPersistenceForSession];

        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


-(void)webservice{

NSString *url= SERVER_URL;

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

 

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

cachePolicy:NSURLRequestUseProtocolCachePolicy

timeoutInterval:30.0];

 

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”

password:@”m2n1shlko”

persistence:NSURLCredentialPersistenceForSession];

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

            break;

        }

    }

}

 

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
                                              animated:YES];
            break;
        }
    }



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:

Blockhead

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