Thursday, 8 March 2018

Web Service Managaer


import UIKit
import Alamofire
import KRProgressHUD

class WebServiceManager: NSObject {
    
    static var instance:WebServiceManager!
    
    class func sharedInstance() -> WebServiceManager {
        self.instance = (self.instance ?? WebServiceManager())
        return self.instance
    }
    
    class func callGeneralWebServiceWithViewController(WSUrl:String,WSMethod:HTTPMethod,WSParams:NSDictionary,isLoader:Bool,iViewController:UIViewController,WSCompletionBlock:@escaping (_ data:AnyObject?,_ error:NSError?) -> ()) {
        
        if self.sharedInstance().ISNetworkAvailable() {
            let iStrWSURL  = Constant.BASE_URL + WSUrl
            
            let url = URL(string: iStrWSURL)
            let aStrDomain = url?.host
            if isLoader {
                KRProgressHUD.show()
            }
            
            Alamofire.request(iStrWSURL, method: WSMethod, parameters: WSParams as? [String : AnyObject], encoding: URLEncoding.httpBody).response(completionHandler: { (iResponse) in
                do
                {
                    let object:Any? = try JSONSerialization.jsonObject(with: iResponse.data!, options:.mutableLeaves)
                    if object! is NSArray
                    {
                        var iArrResponse: NSArray!
                        iArrResponse = object as! NSArray
                        if isLoader {
                            KRProgressHUD.dismiss()
                        }
                        WSCompletionBlock(iArrResponse!,nil)
                    }
                    else
                    {
                        var iDictResponse: Dictionary <String, AnyObject>!
                        iDictResponse = object as! Dictionary
                        if isLoader {
                            KRProgressHUD.dismiss()
                        }
                        WSCompletionBlock(iDictResponse! as AnyObject?,nil)
                    }
                }
                catch let caught as NSError
                {
                    if isLoader {
                        KRProgressHUD.dismiss()
                    }
                    WSCompletionBlock(nil,caught)
                }
                catch
                {
                    KRProgressHUD.dismiss()
                    let error: NSError = NSError(domain: aStrDomain!, code: 1, userInfo: nil)
                    WSCompletionBlock(nil,error)
                }
                
            })
        }else {
            let iAlertController = UIAlertController(title: "", message: "Please check your internet connection", preferredStyle: .alert)
            let iOkAction = UIAlertAction(title: "OK", style: .default, handler: { (iOkAction) in
            })
            iAlertController.addAction(iOkAction)
            iViewController.present(iAlertController, animated: true, completion: nil)
        }
        
    }
    
    class func callGeneralWebService(WSUrl:String,WSParams:NSDictionary,isLoader:Bool,WSCompletionBlock:@escaping (_ data:AnyObject?,_ error:NSError?) -> ()) {
        
        if self.sharedInstance().ISNetworkAvailable() {
            let iStrWSURL  = Constant.BASE_URL + WSUrl
            
            let url = URL(string: iStrWSURL)
            let aStrDomain = url?.host
            if isLoader {
                KRProgressHUD.show()
            }
            
            Alamofire.request(iStrWSURL, method: .post ,parameters: WSParams as? [String : AnyObject]).response(completionHandler: { (iResponse) in
                do
                {
                    let object:Any? = try JSONSerialization.jsonObject(with: iResponse.data!, options:.mutableLeaves)
                    if object! is NSArray
                    {
                        var iArrResponse: NSArray!
                        iArrResponse = object as! NSArray
                        if isLoader {
                            KRProgressHUD.dismiss()
                        }
                        WSCompletionBlock(iArrResponse!,nil)
                    }
                    else
                    {
                        var iDictResponse: Dictionary <String, AnyObject>!
                        iDictResponse = object as! Dictionary
                        if isLoader {
                            KRProgressHUD.dismiss()
                        }
                        WSCompletionBlock(iDictResponse! as AnyObject?,nil)
                    }
                }
                catch let caught as NSError
                {
                    if isLoader {
                        KRProgressHUD.dismiss()
                    }
                    WSCompletionBlock(nil,caught)
                }
                catch
                {
                    KRProgressHUD.dismiss()
                    let error: NSError = NSError(domain: aStrDomain!, code: 1, userInfo: nil)
                    WSCompletionBlock(nil,error)
                }
                
            })
            
        }
        
    }
    
    
    class func callImageUploadWithParameterUsingMultipart(WSUrl:String,WSParams:NSDictionary,isLoader:Bool,iImgName:UIImage, WSCompletionBlock:@escaping (_ data:AnyObject?,_ error:NSError?) -> ()) {
        
        if self.sharedInstance().ISNetworkAvailable()
        {
            //let iURLWS = NSURL(string: CC_Constant.BASE_URL + WSUrl)!
            
            if isLoader {
                KRProgressHUD.show()
            }
            
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(UIImagePNGRepresentation(iImgName)!, withName: "signature_photo", fileName: "swift_file.png", mimeType: "image/png")
                for (key, value) in WSParams {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key as! String)
                }
            }, to:Constant.BASE_URL + WSUrl)
            { (result) in
                switch result {
                case .success(let upload, _, _):
                    
                    upload.uploadProgress(closure: { (progress) in
                        print(progress)
                    })
                    
                    upload.responseJSON { response in
                        if isLoader {
                            KRProgressHUD.dismiss()
                        }
                        print(response.request ?? "")  // original URL request
                        print(response.response ?? "") // URL response
                        print(response.data ?? "")     // server data
                        print(response.result.value ?? "")   // result of response serialization
                        if response.result.value is NSArray
                        {
                            var iArrResponse: NSArray!
                            iArrResponse = response.result.value as! NSArray
                            if isLoader {
                                KRProgressHUD.dismiss()
                            }
                            WSCompletionBlock(iArrResponse!,nil)
                        }
                        else
                        {
                            var iDictResponse: Dictionary <String, AnyObject>!
                            iDictResponse = response.result.value as! Dictionary
                            if isLoader {
                                KRProgressHUD.dismiss()
                            }
                            WSCompletionBlock(iDictResponse! as AnyObject?,nil)
                        }
                        
                    }
                    
                case .failure(let encodingError) :
                    print (encodingError.localizedDescription)
                    if isLoader {
                        KRProgressHUD.dismiss()
                    }
                    WSCompletionBlock(nil,encodingError as NSError?)
                }
            }
        }
    }

    func ISNetworkAvailable() -> Bool
    {
        if Reachability.isInternetAvailable()
        {
            return true
        }
        else
        {
            return false
        }
    }
   // (cell.imageView)?.sd_setImage(with: NSURL(string: imgStr)! as URL, placeholderImage: nil, options: SDWebImageOptions.refreshCached, completed: nil)

}

Friday, 21 October 2016

UITextFiled Class


//  FormTextField.h


#import <UIKit/UIKit.h>

@interface FormTextField : UITextField


/**
 *  Set left Image
 *
 *  @param img UIImage
 */
- (void)setLeftImage:(UIImage *)img;


/**
 *  Set right Image
 *
 *  @param img UIImage
 */
- (void)setRightImage:(UIImage *)img;
- (void)setPlaceholder:(NSString *)placeholder color:(UIColor *)colorName;
- (void)ForTextfield:(UITextField*)textfieldname setBottomBorder:(int)BorderWidth color:(UIColor*)BorderColor;

@end





//  FormTextField.m


#import "FormTextField.h"
#import "UIColor+CustomColor.h"

@interface FormTextField ()

@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;
@property (nonatomic, weak) NSLayoutConstraint *minHeightConstraint;
@property (nonatomic, weak) NSLayoutConstraint *maxHeightConstraint;


@end

@implementation FormTextField


- (instancetype)initWithCoder:(NSCoder *)aDecoder{
   
    self = [super initWithCoder:aDecoder];
   
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)associateConstraints{
   
    // iterate through all text view's constraints and identify
    // height, max height and min height constraints.
   
    for (NSLayoutConstraint *constraint in self.constraints) {
        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
           
            if (constraint.relation == NSLayoutRelationEqual) {
                self.heightConstraint = constraint;
            }
           
            else if (constraint.relation == NSLayoutRelationLessThanOrEqual) {
                self.maxHeightConstraint = constraint;
            }
           
            else if (constraint.relation == NSLayoutRelationGreaterThanOrEqual) {
                self.minHeightConstraint = constraint;
            }
        }
    }
   
}

/**
 *  Default Initialization
 */
- (void)initialize{
   
    [self associateConstraints];
   
    //    self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
   
   // self.borderStyle        = UITextBorderStyleNone;
    self.leftViewMode       = UITextFieldViewModeAlways;
    self.rightViewMode      = UITextFieldViewModeUnlessEditing;
    self.clearButtonMode    = UITextFieldViewModeWhileEditing;
   
    self.textColor          = [UIColor whiteColor];
    self.tintColor          = [UIColor blackColor];
   // self.backgroundColor    = [UIColor colorWithHexaCode:@"82b9fc"];
   
   
   // self.layer.borderColor  = COLOR_BLUE_LIGHT.CGColor;
//    self.layer.borderWidth  = 2;
//    self.layer.cornerRadius = 3;
//   
    //    self.textAlignment = NSTextAlignmentCenter;
   
    [self setPlaceholder:self.placeholder];
   
   
    int minHeight = 40;
   
    if (DEVICE_IS_IPAD){
       
        //self.font               = [UIFont fontWithName:FONT_ROBOTO_REGULAR size:18];
        minHeight  = 50;

    }else{
      //  self.font               = [UIFont fontWithName:FONT_ROBOTO_REGULAR size:12];
    }
   
   
    if (_heightConstraint) {
       
    }else{
        
        _heightConstraint = [NSLayoutConstraint constraintWithItem:self
                                                         attribute:NSLayoutAttributeHeight
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:self
                                                         attribute:NSLayoutAttributeHeight
                                                        multiplier:0.0f
                                                          constant:minHeight
                             ];
       
        [self addConstraint:_heightConstraint];
       
    }

   
}

- (CGRect)rightViewRectForBounds:(CGRect)bounds {
   
    CGRect textRect = [super rightViewRectForBounds:bounds];
    textRect.origin.x -= (DEVICE_IS_IPAD)?10:5;
    return textRect;
   
}

- (CGRect)leftViewRectForBounds:(CGRect)bounds{
   
    CGRect textRect = [super leftViewRectForBounds:bounds];
    textRect.origin.x += (DEVICE_IS_IPAD)?10:5;
    return textRect;
   
}

- (CGRect)clearButtonRectForBounds:(CGRect)bounds{
   
    CGRect textRect = [super clearButtonRectForBounds:bounds];
    textRect.origin.x -= (DEVICE_IS_IPAD)?10:5;
    return textRect;

}

- (CGRect)textRectForBounds:(CGRect)bounds{
    CGRect textRect = [super textRectForBounds:bounds];
    textRect.origin.x += 0; //for space in textfield
    textRect.size.width -= 10;
   
    return textRect;
   
}

- (CGRect)editingRectForBounds:(CGRect)bounds{
   
    CGRect textRect = [super editingRectForBounds:bounds];
    textRect.origin.x += 10;
    textRect.size.width -= 10;
    return textRect;
   
}

- (void)setPlaceholder:(NSString *)placeholder color:(UIColor *)colorName{
   
   // if (self.placeholder.length > 0  )
    if (placeholder.length > 0  ) {
        NSAttributedString *str = [[NSAttributedString alloc]
                                   initWithString:[NSString stringWithFormat:@"%@",placeholder]
                                   attributes:@{
                                                NSForegroundColorAttributeName :colorName,
                                                NSFontAttributeName: self.font
                                                }];
       
      /*  NSAttributedString *str = [[NSAttributedString alloc]
                                   initWithString:[NSString stringWithFormat:@"%@",placeholder]
                                   attributes:@{
                                                NSForegroundColorAttributeName : colorFromRGBA(255,255,255, 1),
                                                NSFontAttributeName: self.font
                                                }];*/
        self.attributedPlaceholder = str;
       
    }
   
}

- (void)layoutSubviews{
 
    [super layoutSubviews];
  
    if (self.isEditing) {
        self.layer.borderColor  = [UIColor whiteColor].CGColor;
    }else{
        self.layer.borderColor  =[UIColor whiteColor].CGColor;
        //COLOR_BLUE_LIGHT.CGColor;
    }

}

/**
 *  Set left Image
 *
 *  @param img UIImage
 */
- (void)setLeftImage:(UIImage *)img{
   
    UIImageView *imageView = [[ UIImageView alloc] init];
   
    if (DEVICE_IS_IPAD) {
        imageView.frame = CGRectMake(10, 5, 40, self.frame.size.height);
    }else{
        imageView.frame = CGRectMake(10, 5, 30, self.frame.size.height);
       
    }
   
    imageView.image  = img;
    imageView.contentMode = UIViewContentModeCenter;
   
    self.leftView = imageView;

   
}

/**
 *  Set right Image
 *
 *  @param img UIImage
 */
- (void)setRightImage:(UIImage *)img{
 
   
    UIImageView *imageView = [[ UIImageView alloc] init];
   
    if (DEVICE_IS_IPAD) {
        imageView.frame = CGRectMake(10, 5, 40, self.frame.size.height-10);
    }else
    {
        imageView.frame = CGRectMake(self.frame.size.width-50, 0, 15, 15);

    }
   
       imageView.image  = img;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:imageView];
   
    self.rightView = imageView;

}

-(void)ForTextfield:(UITextField*)textfieldname setBottomBorder:(int)BorderWidth color:(UIColor*)BorderColor
{
   

    UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, textfieldname.frame.size.height + 15.0f, textfieldname.frame.size.width, 1)];
    bottomBorder.backgroundColor =BorderColor;
    [textfieldname addSubview:bottomBorder];
    //    CALayer *border = [CALayer layer];
   
}


@end



//Use like this : Example -

- (void)setSubView {
   
    [_tfName ForTextfield:_tfName setBottomBorder:1 color:[UIColor darkGrayColor]];
    [_tfEmail ForTextfield:_tfEmail setBottomBorder:1 color:[UIColor darkGrayColor]];
    [_tfComment ForTextfield:_tfComment setBottomBorder:1 color:[UIColor darkGrayColor]];
  
    NSDictionary *attr = @{
                           CustomBorderMarginBottomAttributeName:@5,
                           };
   
    [_telView drawBottomBorder:1 color:[UIColor darkGrayColor] attributes:attr];

}