Facebook login Integration with Browser Or Facebook app Or Popup

Go to https://developers.facebook.com

Create new app

Go to Dashboard

Add product

Select Facebook login

Go to Client OAuth Settings

Client OAuth Login = YES

Web OAuth Login = YES

Go to Facebook Login -> Quick Start -> iOS

Download SDK OR Go to below link

https://origincache.facebook.com/developers/resources/?id=facebook-ios-sdk-current.zip

Go to in your Xcode Project add below four framework

  • Bolts.framework
  • FBSDKLoginKit.framework
  • FBSDKCoreKit.framework
  • FBSDKShareKit.framework

Add your Bundle Identifier

Enable Single Sign On = YES

Right-click your .plist file and choose “Open As Source Code”

Copy and paste the following XML snippet into the body of your file ( <dict>...</dict>)

 

<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb135257030378906</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>135257030378906</string>
<key>FacebookDisplayName</key>
<string>Cherish Gold iOS</string>

 

If you use any of the Facebook dialogs (e.g., Login, Share, App Invites, etc.) that can perform an app switch to Facebook apps, your application’s .plist also need to handle this.

 

<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>

 

Go to Xcode

AppDelegate.h

#import <FBSDKCoreKit/FBSDKCoreKit.h>

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [[FBSDKApplicationDelegate sharedInstance] application:application

                             didFinishLaunchingWithOptions:launchOptions];

    // Override point for customization after application launch.

    return YES;

}

 

– (BOOL)application:(UIApplication *)application openURL:(NSURL *)url

  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application

                                                                  openURL:url

                                                        sourceApplication:sourceApplication

                                                               annotation:annotation

                    ];

    // Add any custom logic here.

    return handled;

}

 

 

ViewController.h

#import <FBSDKCoreKit/FBSDKCoreKit.h>

#import <FBSDKLoginKit/FBSDKLoginKit.h>

#import <FBSDKShareKit/FBSDKShareKit.h>

 

<FBSDKLoginButtonDelegate>

 

– (void)viewDidLoad {

    [super viewDidLoad];

    //Check if User loggedin with FB or not

    if ([FBSDKAccessToken currentAccessToken]) {

        NSLog(@”Account Logged in with FB”);

    }

    else{

        NSLog(@”Please Login with FB”);

    }

    FBSDKLoginButton *facebookLoginButton = [[FBSDKLoginButton alloc] init];

    facebookLoginButton.frame = CGRectMake(100, 100, 300, 50);

    facebookLoginButton.delegate = self;

    [self.view addSubview:facebookLoginButton];

    // Do any additional setup after loading the view, typically from a nib.

}

 

 

– (IBAction)buttonActionFacebookLoginwithSafariorFacebookApp:(id)sender {

    FBSDKLoginManager *fBSDKLoginManager = [[FBSDKLoginManager alloc]init];

    fBSDKLoginManager.loginBehavior = FBSDKLoginBehaviorBrowser;

    [fBSDKLoginManager logInWithReadPermissions:@[@”email”] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

        if (error) {

            NSLog(@”%@”,error);

        }

        else if (result.isCancelled) {

            NSLog(@”result isCancelled”);

        }

        else {

            NSString *stringToken = result.token.tokenString;

            if ([result.grantedPermissions containsObject:@”email”]) {

                [[[FBSDKGraphRequest alloc]initWithGraphPath:@”me” parameters:@{@”fields”:@”id, name, first_name, last_name, gender, picture.type(large), email”}]

                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

                     if (!error) {

                         NSLog(@”%@”,result);

                         NSMutableDictionary *dictionaryFbSDKResponce = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                                         stringToken,@”toekn”,

                                                                         [result valueForKey:@”id”],@”id”,

                                                                         [result valueForKey:@”name”],@”name”,

                                                                         [result valueForKey:@”first_name”],@”first_name”,

                                                                         [result valueForKey:@”last_name”],@”last_name”,

                                                                         [result valueForKey:@”gender”],@”gender”,

                                                                         [result valueForKeyPath:@”picture.data.url”],@”picture”,

                                                                         [result valueForKey:@”email”],@”email”, nil];

                         NSLog(@”%@”,dictionaryFbSDKResponce);

                         //Navigate to HomeScreenViewController

                     }

                     else {

                         NSLog(@”%@”,[error localizedDescription]);

                         NSLog(@”%@”,error);

                     }

                 }];

            }

        }

    }];

}

– (IBAction)buttonActionFacebookLoginwithPopup:(id)sender {

    FBSDKLoginManager *fBSDKLoginManager = [[FBSDKLoginManager alloc]init];

    fBSDKLoginManager.loginBehavior = FBSDKLoginBehaviorWeb;

    [fBSDKLoginManager logInWithReadPermissions:@[@”email”] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

        if (error) {

            NSLog(@”%@”,error);

        }

        else if (result.isCancelled) {

            NSLog(@”result isCancelled”);

        }

        else {

            NSString *stringToken = result.token.tokenString;

            if ([result.grantedPermissions containsObject:@”email”]) {

                [[[FBSDKGraphRequest alloc]initWithGraphPath:@”me” parameters:@{@”fields”:@”id, name, first_name, last_name, gender, picture.type(large), email”}]

                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

                     if (!error) {

                         NSLog(@”%@”,result);

                         NSMutableDictionary *dictionaryFbSDKResponce = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                                         stringToken,@”toekn”,

                                                                         [result valueForKey:@”id”],@”id”,

                                                                         [result valueForKey:@”name”],@”name”,

                                                                         [result valueForKey:@”first_name”],@”first_name”,

                                                                         [result valueForKey:@”last_name”],@”last_name”,

                                                                         [result valueForKey:@”gender”],@”gender”,

                                                                         [result valueForKeyPath:@”picture.data.url”],@”picture”,

                                                                         [result valueForKey:@”email”],@”email”, nil];

                         NSLog(@”%@”,dictionaryFbSDKResponce);

                         //Navigate to HomeScreenViewController

                     }

                     else {

                         NSLog(@”%@”,[error localizedDescription]);

                         NSLog(@”%@”,error);

                     }

                 }];

            }

        }

    }];

}

#pragma mark – FBSDKLoginButtonDelegate

– (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {

    //After Secessful login this method will fire

    NSLog(@”%@”,loginButton);

    NSLog(@”%@”,result);

    NSLog(@”%@”,error);

    if (error) {

        NSLog(@”%@”,error);

    }

    else if (result.isCancelled) {

        NSLog(@”result isCancelled”);

    }

    else {

        NSString *stringToken = result.token.tokenString;

        if ([result.grantedPermissions containsObject:@”email”]) {

            [[[FBSDKGraphRequest alloc]initWithGraphPath:@”me” parameters:@{@”fields”:@”id, name, first_name, last_name, gender, picture.type(large), email”}]

             startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

                 if (!error) {

                     NSLog(@”%@”,result);

                     NSMutableDictionary *dictionaryFbSDKResponce = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                                     stringToken,@”toekn”,

                                                                     [result valueForKey:@”id”],@”id”,

                                                                     [result valueForKey:@”name”],@”name”,

                                                                     [result valueForKey:@”first_name”],@”first_name”,

                                                                     [result valueForKey:@”last_name”],@”last_name”,

                                                                     [result valueForKey:@”gender”],@”gender”,

                                                                     [result valueForKeyPath:@”picture.data.url”],@”picture”,

                                                                     [result valueForKey:@”email”],@”email”, nil];

                     NSLog(@”%@”,dictionaryFbSDKResponce);

                     //Navigate to HomeScreenViewController

                 }

                 else {

                     NSLog(@”%@”,[error localizedDescription]);

                     NSLog(@”%@”,error);

                 }

             }];

        }

    }

}

– (void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton {

    // After Logout button this method will fire

    NSLog(@”%@”,loginButton);

}

– (BOOL) loginButtonWillLogin:(FBSDKLoginButton *)loginButton {

    //Before Login and Logout button this method will fire

    //Enable Or Desable Facebook Login

    NSLog(@”%@”,loginButton);

    return true;

}

 

Download Sample Project From Github

 

Typedef void Use in Project

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    

    NSLog(@”%ld”,(long)indexPath.row);

    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

    

//    // animate the cell user tapped on

//    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

//    

//    aFrame = cell.frame;

//    aIndexPath = indexPath;

//    

//    NSLog(@”%f”,WD);

//    NSLog(@”%f”,HT);

//    

//    [UIView animateWithDuration:1.0

//                          delay:0

//                        options:(UIViewAnimationOptionAllowUserInteraction)

//                     animations:^{

//                         NSLog(@”animation start”);

//                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

//                         [self.collectionView bringSubviewToFront:cell];

//                     }

//                     completion:^(BOOL finished){

//                         NSLog(@”animation end”);

//                        // [cell setBackgroundColor:[UIColor whiteColor]];

//                         

//                     }

//     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

Download Sample Project From GitHub

Switch Set Image and Change Background Color

Reference From :: ZJSwitch

 

ViewController.h

#import <UIKit/UIKit.h>

#import “ZJSwitch.h”

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *viewForSwitchFirst;

@property (weak, nonatomic) IBOutlet UIView *viewForSwitchTwo;

@property (weak, nonatomic) IBOutlet UISwitch *SwitchOnOff;

– (IBAction)switchActionOnOff:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

//    self.SwitchOnOff.onImage = [UIImage imageNamed:@”toggle-from.png”];

//    self.SwitchOnOff.offImage = [UIImage imageNamed:@”toggle-to.png”];

    

    

    CGFloat r1 = CGRectGetHeight(self.viewForSwitchFirst.bounds) / 2.0;

    self.viewForSwitchFirst.layer.cornerRadius = r1;

    

    ZJSwitch *switch1 = [[ZJSwitch alloc] initWithFrame:CGRectMake(5, 5, self.viewForSwitchFirst.frame.size.width10, self.viewForSwitchFirst.frame.size.height10)];

    switch1.on = YES;

    switch1.backgroundColor = [UIColor clearColor];

    switch1.onTintColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:255/255.0 alpha:1];

    switch1.offTintColor = [UIColor colorWithRed:0/255.0 green:255/255.0 blue:0/255.0 alpha:1];

    switch1.textColor = [UIColor blackColor];

    switch1.onText = @”Switch ON”;

    switch1.offText = @”Switch OFF”;

    //switch2.textFont = @””;

    [switch1 setOnTextFontSize:10];

    [switch1 setOffTextFontSize:10];

    [switch1 addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitchFirst addSubview:switch1];

    

    

    CGFloat r2 = CGRectGetHeight(self.viewForSwitchTwo.bounds) / 2.0;

    self.viewForSwitchTwo.layer.cornerRadius = r2;

    

    ZJSwitch *switch2 = [[ZJSwitch alloc] initWithFrame:CGRectMake(5, 5, self.viewForSwitchTwo.frame.size.width10, self.viewForSwitchTwo.frame.size.height10)];

    switch2.on = YES;

    switch2.backgroundColor = [UIColor clearColor];

    switch2.tintColor = [UIColor orangeColor];

    [switch2 addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitchTwo addSubview:switch2];

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)switchActionOnOff:(id)sender

{

    NSLog(@”%@”,sender);

    

    if ([self.SwitchOnOff isOn])

    {

        NSLog(@”Switch id On”);

    }

    else

    {

        NSLog(@”Switch is Off”);

    }

}

– (void)handleSwitchEvent:(id)sender

{

    if ([sender isOn])

    {

        NSLog(@”Switch is On”);

    }

    else

    {

        NSLog(@”Switch is Off”);

    }

}

@end

ZJSwitch.h

#import <UIKit/UIKit.h>

@interface ZJSwitch : UIControl

@property (nonatomic, assign, getter = isOn) BOOL on;

@property (nonatomic, strong) UIColor *onTintColor;

@property (nonatomic, strong) UIColor *offTintColor;

@property (nonatomic, strong) UIColor *thumbTintColor;

@property (nonatomic, strong) UIColor *textColor;

@property (nonatomic, strong) UIFont *textFont;

@property (nonatomic, strong) NSString *onText;

@property (nonatomic, strong) NSString *offText;

– (void)setTextFont:(UIFont *)textFont;

– (void)setOnTextFontSize:(CGFloat)onTextFontSize;

– (void)setOffTextFontSize:(CGFloat)offTextFontSize;

– (void)setOn:(BOOL)on animated:(BOOL)animated;

@end

ZJSwitch.m

#import “ZJSwitch.h”

#define ZJSwitchMaxHeight 100.0f

#define ZJSwitchMinHeight 20.0f

#define ZJSwitchMinWidth 30.0f

#define ZJSwitchKnobSize 15.0f

@interface ZJSwitch ()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UIView *onContentView;

@property (nonatomic, strong) UIView *offContentView;

@property (nonatomic, strong) UIView *knobView;

@property (nonatomic, strong) UILabel *onLabel;

@property (nonatomic, strong) UILabel *offLabel;

– (void)commonInit;

– (CGRect)roundRect:(CGRect)frameOrBounds;

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer;

– (void)handlePanGestureRecognizerEvent:(UIPanGestureRecognizer *)recognizer;

@end

@implementation ZJSwitch

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:[self roundRect:frame]];

    if (self) {

        [self commonInit];

    }

    return self;

}

– (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super initWithCoder:aDecoder];

    

    if (self) {

        [self commonInit];

    }

    

    return self;

}

– (void)setBounds:(CGRect)bounds

{

    [super setBounds:[self roundRect:bounds]];

    

    [self setNeedsLayout];

}

– (void)setFrame:(CGRect)frame

{

    [super setFrame:[self roundRect:frame]];

    

    [self setNeedsLayout];

}

– (void)setTextFont:(UIFont *)textFont

{

    _onLabel.font = textFont;

    _offLabel.font = textFont;

    

}

– (void)setOnText:(NSString *)onText

{

    if (_onText != onText) {

        _onText = onText;

        

        _onLabel.text = onText;

    }

}

– (void)setOffText:(NSString *)offText

{

    if (_offText != offText) {

        _offText = offText;

        

        _offLabel.text = offText;

    }

}

– (void)setOnTextFontSize:(CGFloat)onTextFontSize

{

    [_onLabel setFont:[UIFont systemFontOfSize:onTextFontSize]];

    

}

– (void)setOffTextFontSize:(CGFloat)offTextFontSize

{

     [_offLabel setFont:[UIFont systemFontOfSize:offTextFontSize]];

}

– (void)setOnTintColor:(UIColor *)onTintColor

{

    if (_onTintColor != onTintColor) {

        _onTintColor = onTintColor;

        

        _onContentView.backgroundColor = onTintColor;

    }

}

– (void)setOffTintColor:(UIColor *)offTintColor

{

    if (_offTintColor != offTintColor) {

        _offTintColor = offTintColor;

        

        _offContentView.backgroundColor = offTintColor;

    }

}

– (void)setThumbTintColor:(UIColor *)thumbTintColor

{

    if (_thumbTintColor != thumbTintColor) {

        _thumbTintColor = thumbTintColor;

        

        _knobView.backgroundColor = _thumbTintColor;

    }

}

– (void)layoutSubviews

{

    [super layoutSubviews];

    

    self.containerView.frame = self.bounds;

    

    CGFloat r = CGRectGetHeight(self.containerView.bounds) / 2.0;

    

    self.containerView.layer.cornerRadius = r;

    self.containerView.layer.masksToBounds = YES;

    

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    

    if (!self.isOn) {

        // frame of off status

        self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                              0,

                                              CGRectGetWidth(self.containerView.bounds),

                                              CGRectGetHeight(self.containerView.bounds));

        

        self.offContentView.frame = CGRectMake(0,

                                               0,

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetHeight(self.containerView.bounds));

        

        self.knobView.frame = CGRectMake(margin,

                                         margin,

                                         ZJSwitchKnobSize,

                                         ZJSwitchKnobSize);

    } else {

        // frame of on status

        self.onContentView.frame = CGRectMake(0,

                                              0,

                                              CGRectGetWidth(self.containerView.bounds),

                                              CGRectGetHeight(self.containerView.bounds));

        

        self.offContentView.frame = CGRectMake(0,

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetHeight(self.containerView.bounds));

        

        self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                         margin,

                                         ZJSwitchKnobSize,

                                         ZJSwitchKnobSize);

    }

    

    CGFloat lHeight = 20.0f;

    CGFloat lMargin = r – (sqrtf(powf(r, 2) – powf(lHeight / 2.0, 2))) + margin;

    

    self.onLabel.frame = CGRectMake(lMargin,

                                    r – lHeight / 2.0,

                                    CGRectGetWidth(self.onContentView.bounds) – lMargin – ZJSwitchKnobSize2 * margin,

                                    lHeight);

    

    self.offLabel.frame = CGRectMake(ZJSwitchKnobSize + 2 * margin,

                                     r – lHeight / 2.0,

                                     CGRectGetWidth(self.onContentView.bounds) – lMargin – ZJSwitchKnobSize2 * margin,

                                     lHeight);

}

– (void)setOn:(BOOL)on

{

    [self setOn:on animated:NO];

}

– (void)setOn:(BOOL)on animated:(BOOL)animated

{

    if (_on == on) {

        return;

    }

    

    _on = on;

    

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    

    if (!animated) {

        if (!self.isOn) {

            // frame of off status

            self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                                  0,

                                                  CGRectGetWidth(self.containerView.bounds),

                                                  CGRectGetHeight(self.containerView.bounds));

            

            self.offContentView.frame = CGRectMake(0,

                                                   0,

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetHeight(self.containerView.bounds));

            

            self.knobView.frame = CGRectMake(margin,

                                             margin,

                                             ZJSwitchKnobSize,

                                             ZJSwitchKnobSize);

        } else {

            // frame of on status

            self.onContentView.frame = CGRectMake(0,

                                                  0,

                                                  CGRectGetWidth(self.containerView.bounds),

                                                  CGRectGetHeight(self.containerView.bounds));

            

            self.offContentView.frame = CGRectMake(0,

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetHeight(self.containerView.bounds));

            

            self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                             margin,

                                             ZJSwitchKnobSize,

                                             ZJSwitchKnobSize);

        }

    } else {

        if (self.isOn) {

            [UIView animateWithDuration:0.25

                             animations:^{

                                 self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                                                  margin,

                                                                  ZJSwitchKnobSize,

                                                                  ZJSwitchKnobSize);

                             }

                             completion:^(BOOL finished){

                                 self.onContentView.frame = CGRectMake(0,

                                                                       0,

                                                                       CGRectGetWidth(self.containerView.bounds),

                                                                       CGRectGetHeight(self.containerView.bounds));

                                 

                                 self.offContentView.frame = CGRectMake(0,

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetHeight(self.containerView.bounds));

                             }];

        } else {

            [UIView animateWithDuration:0.25

                             animations:^{

                                 self.knobView.frame = CGRectMake(margin,

                                                                  margin,

                                                                  ZJSwitchKnobSize,

                                                                  ZJSwitchKnobSize);

                             }

                             completion:^(BOOL finished){

                                 self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                                                       0,

                                                                       CGRectGetWidth(self.containerView.bounds),

                                                                       CGRectGetHeight(self.containerView.bounds));

                                 

                                 self.offContentView.frame = CGRectMake(0,

                                                                        0,

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetHeight(self.containerView.bounds));

                             }];

        }

    }

    

    [self sendActionsForControlEvents:UIControlEventValueChanged];

}

#pragma mark – Private API

– (void)commonInit

{

    self.backgroundColor = [UIColor clearColor];

    

    _onTintColor = [UIColor colorWithRed:130 / 255.0 green:200 / 255.0 blue:90 / 255.0 alpha:1.0];

    _offTintColor = [UIColor colorWithWhite:0.75 alpha:1.0];

    _thumbTintColor = [UIColor colorWithWhite:1.0 alpha:1.0];

    

    _textFont = [UIFont systemFontOfSize:10.0f];

    _textColor = [UIColor whiteColor];

    

    _containerView = [[UIView alloc] initWithFrame:self.bounds];

    _containerView.backgroundColor = [UIColor clearColor];

    [self addSubview:_containerView];

    

    _onContentView = [[UIView alloc] initWithFrame:self.bounds];

    _onContentView.backgroundColor = _onTintColor;

    [_containerView addSubview:_onContentView];

    

    _offContentView = [[UIView alloc] initWithFrame:self.bounds];

    _offContentView.backgroundColor = _offTintColor;

    [_containerView addSubview:_offContentView];

    

    _knobView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZJSwitchKnobSize, ZJSwitchKnobSize)];

    _knobView.backgroundColor = _thumbTintColor;

    _knobView.layer.cornerRadius = (ZJSwitchKnobSize / 2.0);

    [_containerView addSubview:_knobView];

    

    _onLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    _onLabel.backgroundColor = [UIColor clearColor];

    _onLabel.textAlignment = NSTextAlignmentCenter;

    _onLabel.textColor = _textColor;

    _onLabel.font = _textFont;

    _onLabel.text = _onText;

    [_onContentView addSubview:_onLabel];

    

    _offLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    _offLabel.backgroundColor = [UIColor clearColor];

    _offLabel.textAlignment = NSTextAlignmentCenter;

    _offLabel.textColor = _textColor;

    _offLabel.font = _textFont;

    _offLabel.text = _offText;

    [_offContentView addSubview:_offLabel];

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self addGestureRecognizer:tapGesture];

    

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handlePanGestureRecognizerEvent:)];

    [self addGestureRecognizer:panGesture];

}

– (CGRect)roundRect:(CGRect)frameOrBounds

{

    CGRect newRect = frameOrBounds;

    

    if (newRect.size.height > ZJSwitchMaxHeight) {

        newRect.size.height = ZJSwitchMaxHeight;

    }

    

    if (newRect.size.height < ZJSwitchMinHeight) {

        newRect.size.height = ZJSwitchMinHeight;

    }

    

    if (newRect.size.width < ZJSwitchMinWidth) {

        newRect.size.width = ZJSwitchMinWidth;

    }

    

    return newRect;

}

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    if (recognizer.state == UIGestureRecognizerStateEnded) {

        [self setOn:!self.isOn animated:NO];

    }

}

– (void)handlePanGestureRecognizerEvent:(UIPanGestureRecognizer *)recognizer

{

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    CGFloat offset = 6.0f;

    

    switch (recognizer.state) {

        case UIGestureRecognizerStateBegan:{

            if (!self.isOn) {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(margin,

                                                                      margin,

                                                                      ZJSwitchKnobSize + offset,

                                                                      ZJSwitchKnobSize);

                                 }];

            } else {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – (ZJSwitchKnobSize + offset),

                                                                      margin,

                                                                      ZJSwitchKnobSize + offset,

                                                                      ZJSwitchKnobSize);

                                 }];

            }

            break;

        }

        case UIGestureRecognizerStateCancelled:

        case UIGestureRecognizerStateFailed: {

            if (!self.isOn) {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(margin,

                                                                      margin,

                                                                      ZJSwitchKnobSize,

                                                                      ZJSwitchKnobSize);

                                 }];

            } else {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – ZJSwitchKnobSize,

                                                                      margin,

                                                                      ZJSwitchKnobSize,

                                                                      ZJSwitchKnobSize);

                                 }];

            }

            break;

        }

        case UIGestureRecognizerStateChanged:{

            break;

        }

        case UIGestureRecognizerStateEnded:

            [self setOn:!self.isOn animated:YES];

            break;

        case UIGestureRecognizerStatePossible:

            break;

    }

}

@end

Download Sample Project From GitHub

Singleton Method

ViewController.h

#import <UIKit/UIKit.h>

#import “SingletonClass.h”

@interface ViewController : UIViewController

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *stringFirst = @”First”;

    NSString *stringSecond = @”Second”;

    NSString *stringConcatenated;

    stringConcatenated = [[SingletonClass sharedSingletonClass]twoStringConcatenationFirstString:stringFirst SeconString:stringSecond];

    NSLog(@”%@”,stringConcatenated);

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

SingletonClass.h

#import <Foundation/Foundation.h>

@interface SingletonClass : NSObject

+ (SingletonClass *)sharedSingletonClass;

– (NSString *)twoStringConcatenationFirstString:(NSString *)aFirstString SeconString:(NSString *)aSecondString;

@end

SingletonClass.m

#import “SingletonClass.h”

@implementation SingletonClass

+ (SingletonClass *)sharedSingletonClass

{

    static SingletonClass *sharedInstance = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^

                  {

                      sharedInstance = [[self alloc]init];

                  });

    return sharedInstance;

}

– (NSString *)twoStringConcatenationFirstString:(NSString *)aFirstString SeconString:(NSString *)aSecondString

{

    NSString *strinfConcatenation;

    strinfConcatenation = [aFirstString stringByAppendingString:aSecondString];

    return strinfConcatenation;

}

@end

Download Sample Project From GitHub

SignUp Screen and use NSNotificationCenter defaultCenter for Show Hide Keyboard

– (void)viewDidLoad {

    [super viewDidLoad];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

    UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];

    aGest.numberOfTapsRequired = 1;

    [self.ScrlViewSignUpVC addGestureRecognizer:aGest];

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillShowNotification

                                                  object:nil];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillHideNotification

                                                  object:nil];

}

#pragma mark – Gester method

– (void)tapDetected {

    [self.currentTextField resignFirstResponder];

}

#pragma mark – UIKeyboard show/hide notification

– (void)keyboardWillShow:(NSNotification *)iNotification {

    

    NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);

    NSDictionary *aKeyInfo = iNotification.userInfo;

    NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect aRect = [aRectValue CGRectValue];

    if (self.currentTextField.tag == 5 || self.currentTextField.tag == 6 || self.currentTextField.tag == 7) {

        self.ScrlViewSignUpVC.contentOffset = CGPointMake(0, (aRect.size.height) – 50);

    }

}

– (void)keyboardWillHide:(NSNotification *)iNotification  {

    self.ScrlViewSignUpVC.contentOffset = CGPointMake(0, 0);

}

#pragma mark – UITextField delegate

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];

    return YES;

}

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

    self.currentTextField = textField;

}

Download Sample Project From GitHub

ScrollView Auto Layout for SignUp And keyboard Show Hide With Notification

ViewController.h

#import <UIKit/UIKit.h>

#import “NewViewController.h”

#import “UserDetailDataModel.h”

@interface ViewController : UIViewController<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textFieldCurrent;

@property (weak, nonatomic) IBOutlet UITextField *textFieldFirstName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldLastName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPhoneNumber;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewSignUp;

– (IBAction)buttonActionSubmit:(id)sender;

– (IBAction)buttonActionCancel:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

    

    UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];

    aGest.numberOfTapsRequired = 1;

    [self.view addGestureRecognizer:aGest];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillShowNotification

                                                  object:nil];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillHideNotification

                                                  object:nil];

}

– (IBAction)buttonActionSubmit:(id)sender

{

    NSLog(@”buttonActionSubmit”);

    

    UserDetailDataModel *aUserDetailDataModel = [UserDetailDataModel new];

    aUserDetailDataModel.FirstName = self.textFieldFirstName.text;

    aUserDetailDataModel.LastName = self.textFieldLastName.text;

    aUserDetailDataModel.PhoneNumber = self.textFieldPhoneNumber.text;

    aUserDetailDataModel.City = self.textFieldCity.text;

    

    NewViewController *aNewViewController = [self.storyboard instantiateViewControllerWithIdentifier:@”NewViewController”];

    aNewViewController.bUserDetailDataModel = aUserDetailDataModel;

    [self.navigationController pushViewController:aNewViewController animated:YES];

}

– (IBAction)buttonActionCancel:(id)sender

{

    NSLog(@”buttonActionCancel”);

    [self resetAllTextField];

}

– (void)resetAllTextField

{

    self.textFieldFirstName.text = nil;

    self.textFieldLastName.text = nil;

    self.textFieldPhoneNumber.text = nil;

    self.textFieldCity.text = nil;

}

#pragma mark – Gester method

– (void)tapDetected {

    

    [self.textFieldCurrent resignFirstResponder];

    

}

#pragma mark – UIKeyboard show/hide notification

– (void)keyboardWillShow:(NSNotification *)iNotification {

    

    NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);

    

    NSDictionary *aKeyInfo = iNotification.userInfo;

    NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect aRect = [aRectValue CGRectValue];

    

    if (self.textFieldCurrent.tag == 3 || self.textFieldCurrent.tag == 4)

    {

        self.scrollViewSignUp.contentOffset = CGPointMake(0, (aRect.size.height) – ([UIScreen mainScreen].bounds.size.height / 5.3));

    }

    

}

– (void)keyboardWillHide:(NSNotification *)iNotification  {

    

    self.scrollViewSignUp.contentOffset = CGPointMake(0, 0);

    

}

#pragma mark – UITextField delegate

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    

    [textField resignFirstResponder];

    return YES;

    

}

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

    

    self.textFieldCurrent = textField;

    

}

@end

NewViewController.h

#import <UIKit/UIKit.h>

#import “UserDetailDataModel.h”

#import “Utility.h”

@interface NewViewController : UIViewController

@property (strong, nonatomic) UserDetailDataModel *bUserDetailDataModel;

– (IBAction)buttonActionBack:(id)sender;

@end

NewViewController.m

#import “NewViewController.h”

@interface NewViewController ()

@end

@implementation NewViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,self.bUserDetailDataModel);

    NSLog(@”%@”,[self.bUserDetailDataModel asMutableDictionaryUserDetailDataModel]);

    NSLog(@”%@”,[Utility descriptionForObject:self.bUserDetailDataModel]);

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)buttonActionBack:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

@end

UserDetailDataModel.h

#import <Foundation/Foundation.h>

@interface UserDetailDataModel : NSObject

@property (strong, nonatomic) NSString *FirstName;

@property (strong, nonatomic) NSString *LastName;

@property (strong, nonatomic) NSString *PhoneNumber;

@property (strong, nonatomic) NSString *City;

– (NSMutableDictionary *)asMutableDictionaryUserDetailDataModel;

@end

UserDetailDataModel.m

#import “UserDetailDataModel.h”

@implementation UserDetailDataModel

– (NSMutableDictionary *)asMutableDictionaryUserDetailDataModel

{

    NSMutableDictionary *aDictionaryUserDetailDataModel = [NSMutableDictionary new];

    [aDictionaryUserDetailDataModel setObject:(self.FirstName == nil ? @””:self.FirstName) forKey:@”FirstName”];

    [aDictionaryUserDetailDataModel setObject:(self.LastName == nil ? @””:self.LastName) forKey:@”LastName”];

    [aDictionaryUserDetailDataModel setObject:(self.PhoneNumber == nil ? @””:self.PhoneNumber) forKey:@”PhoneNumber”];

    [aDictionaryUserDetailDataModel setObject:(self.City == nil ? @””:self.City) forKey:@”City”];

    

    return aDictionaryUserDetailDataModel;

}

@end

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”\n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

Download Sample Project From GitHub

Plist File Data Save

#import “ViewController.h”

@interface ViewController ()

@property (strong, nonatomic) NSMutableArray *names, *populations;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Cities” ofType:@”plist”];

    NSData *data = [NSData dataWithContentsOfFile:filePath];

    NSPropertyListFormat format;

    NSString *error;

    id fileContents = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];

    self.populations = [[fileContents objectForKey:@”City Population”] mutableCopy];

    self.names = [[fileContents objectForKey:@”City Names”] mutableCopy];

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

Download Sample Project From GitHub

PDF Generate Write Text Line Add Image

ViewController.h

 

#import <UIKit/UIKit.h>

#define kPadding 20

@interface ViewController : UIViewController

{

    CGSize _pageSize;

}

– (IBAction)btnCreatePDFPress:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

   

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (void)setupPDFDocumentNamed:(NSString*)name Width:(float)width Height:(float)height

{

  _pageSize = CGSizeMake(width, height);

    NSString *newPDFName = [NSString stringWithFormat:@”%@.pdf”, name];

    

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    

    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];

    NSLog(@”%@”,pdfPath);

    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);

    

}

– (void)beginPDFPage {

    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, _pageSize.width, _pageSize.height), nil);

}

– (IBAction)btnCreatePDFPress:(id)sender {

    

    

     [self setupPDFDocumentNamed:@”NewPDF” Width:850 Height:1100];

    

    

    [self beginPDFPage];

    CGRect textRect = [self addText:@”USA is great Country”

                          withFrame:CGRectMake(kPadding, kPadding, 400, 200) fontSize:48.0f];

    

    CGRect textRect1 = [self addText:@”USA has power”

                          withFrame:CGRectMake(kPadding, 500, 400, 200) fontSize:48.0f];

    

    CGRect blueLineRect = [self addLineWithFrame:CGRectMake(kPadding, textRect.origin.y + textRect.size.height + kPadding, _pageSize.widthkPadding*2, 4)

                                       withColor:[UIColor blueColor]];

    

    UIImage *anImage = [UIImage imageNamed:@”download.png”];

    CGRect imageRect = [self addImage:anImage

                              atPoint:CGPointMake((_pageSize.width/2)-(anImage.size.width/2), blueLineRect.origin.y + blueLineRect.size.height + kPadding)];

    

    [self addLineWithFrame:CGRectMake(kPadding, imageRect.origin.y + imageRect.size.height + kPadding, _pageSize.widthkPadding*2, 4)

                 withColor:[UIColor redColor]];

    

    [self finishPDF];

    

}

– (CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize

{

    UIFont *font = [UIFont systemFontOfSize:fontSize];

    CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(_pageSize.width2*202*20, _pageSize.height2*202*20) lineBreakMode:UILineBreakModeWordWrap];

    

    float textWidth = frame.size.width;

    

    if (textWidth < stringSize.width)

        textWidth = stringSize.width;

    if (textWidth > _pageSize.width)

        textWidth = _pageSize.width – frame.origin.x;

    

    CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

    

    [text drawInRect:renderingRect

            withFont:font

       lineBreakMode:UILineBreakModeWordWrap

           alignment:UITextAlignmentLeft];

    

    frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

    return frame;

}

  (CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color

{

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    

    CGContextSetStrokeColorWithColor(currentContext, color.CGColor);

    // this is the thickness of the line

    CGContextSetLineWidth(currentContext, frame.size.height);

    

    CGPoint startPoint = frame.origin;

    CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width, frame.origin.y);

    

    CGContextBeginPath(currentContext);

    CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);

    CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);

    

    CGContextClosePath(currentContext);

    CGContextDrawPath(currentContext, kCGPathFillStroke);

    return  frame;

}

– (CGRect)addImage:(UIImage*)image atPoint:(CGPoint)point

{

    CGRect imageFrame = CGRectMake(point.x, point.y, image.size.width, image.size.height);

    [image drawInRect:imageFrame];

    

    return imageFrame;

}

– (void)finishPDF {

    UIGraphicsEndPDFContext();

}

@end

Download Sample Project From GitHub

 

PDF Generate from View

 

– (IBAction)btnGeneratePDFPress:(id)sender

{

    

    [self createPDFfromUIView:self.view saveToDocumentsWithFileName:@”NewPDF.pdf”];

    

}

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename

{

    // Creates a mutable data object for updating with binary data, like a byte array

    NSMutableData *pdfData = [NSMutableData data];

    

    // Points the pdf converter to the mutable data object and to the UIView to be converted

    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);

    UIGraphicsBeginPDFPage();

    CGContextRef pdfContext = UIGraphicsGetCurrentContext();

    

    

    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

    

    [aView.layer renderInContext:pdfContext];

    

    // remove PDF rendering context

    UIGraphicsEndPDFContext();

    

    // Retrieves the document directories from the iOS device

    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];

    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    

    // instructs the mutable data object to write its context to a file on disk

    [pdfData writeToFile:documentDirectoryFilename atomically:YES];

    NSLog(@”documentDirectoryFileName: %@”,documentDirectoryFilename);

}

Download Sample Project From GitHub

Data Pass with Navigation Segue

FPProductListViewController.h

#import <UIKit/UIKit.h>

#import “FPProductDetailViewController.h”

#import “FPCartViewController.h”

@interface FPProductListViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

{

    NSArray *arysampleData;

}

@property (strong, nonatomic) NSMutableDictionary *dicProductDetailFrmProdctLst;

@property (strong, nonatomic) NSMutableArray *arySelectedProductsFrmPrdctLst;

@property (strong, nonatomic) NSArray *aryTableData;

@property (strong, nonatomic) IBOutlet UITableView *tblVwProductList;

– (IBAction)btnBackClicked:(id)sender;

– (IBAction)btnCartClicked:(id)sender;

@end

FPProductListViewController.m

#import “FPProductListViewController.h”

@interface FPProductListViewController ()

@end

@implementation FPProductListViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    

    

    arysampleData = @[ @{ @”description”: @”2016-06-14″,

                            @”Blocks”: @[ @{ @”title”: @”Block A1″,@”image”:@”0.png” },

                                          @{ @”title”: @”Block A2″,@”image”:@”1.png” },

                                          @{ @”title”: @”Block A3″,@”image”:@”3.png” },

                                          @{ @”title”: @”Block A4″,@”image”:@”4.png” },

                                          @{ @”title”: @”Block A5″,@”image”:@”5.png” },

                                          @{ @”title”: @”Block A6″,@”image”:@”6.png” },

                                          @{ @”title”: @”Block A7″,@”image”:@”7.png” },

                                          @{ @”title”: @”Block A8″,@”image”:@”8.png” },

                                          @{ @”title”: @”Block A9″,@”image”:@”9.png” },

                                          @{ @”title”: @”Block A10″,@”image”:@”10.png” }

                                          ]

                            },

                         @{ @”description”: @”2016-06-21″,

                            @”Blocks”: @[ @{ @”title”: @”Block B1″,@”image”:@”11.png” },

                                          @{ @”title”: @”Block B2″,@”image”:@”12.png” },

                                          @{ @”title”: @”Block B3″,@”image”:@”13.png” },

                                          @{ @”title”: @”Block B4″,@”image”:@”14.png” },

                                          @{ @”title”: @”Block B5″,@”image”:@”15.png” }

                                          ]

                            },

                         @{ @”description”: @”2015-09-30″,

                            @”Blocks”: @[ @{ @”title”: @”Block C1″,@”image”:@”0.png” },

                                          @{ @”title”: @”Block C2″,@”image”:@”2.png” },

                                          @{ @”title”: @”Block C3″,@”image”:@”4.png” },

                                          @{ @”title”: @”Block C4″,@”image”:@”6.png” },

                                          @{ @”title”: @”Block C5″,@”image”:@”8.png” }

                                          ]

                            },

                         ];

//    NSSortDescriptor *discriptor = [[NSSortDescriptor alloc]initWithKey:@”description” ascending:YES];

//    NSArray *descriptors = [NSArray arrayWithObject:discriptor];

//    self.aryTableData = [arysampleData sortedArrayUsingDescriptors:descriptors];

    

    

//    NSLog(@”%@”,arysampleData);

    

    

    self.aryTableData = @[ @{ @”product name”: @”Coverage Products”,

                              @”product detail”: @[@{@”ProductId”: @”1″,@”image”: @”Productimage1″,@”name”: @”SurgeShield Only”,@”detail”: @”SurgeShield is a whole-house surge protection program administered by FPL Energy Services, Inc”,@”price”:@”9.95″,@”productQuantity”: @”1″},

                                           @{@”ProductId”: @”2″,@”image”: @”Productimage2″,@”name”: @”Electronics Surge Protection Only”,@”detail”: @”surge protector. Most designs serve one immediately obvious function — they let you plug multiple components into one power outlet.”,@”price”:@”9.95″,@”productQuantity”: @”1″},

                                           @{@”ProductId”: @”3″,@”image”: @”Productimage3″,@”name”: @”Surge Protection Bundle”,@”detail”: @” Surge Protector Strip gives you the power you need for your electronic devices.”,@”price”:@”14.95″,@”productQuantity”: @”1″}]

                              },

                           ];

   NSLog(@”%@”,self.aryTableData);

    

    

    

    self.arySelectedProductsFrmPrdctLst = [[NSMutableArray alloc]init];

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma mark – UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return [self.aryTableData count];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [[[self.aryTableData objectAtIndex:section] objectForKey:@”product detail”]count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    

    static NSString *cellIdentifier = @”Cell”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    

    

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

    

    UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:100];

    imageViewProductImage.image = [UIImage imageNamed:[[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”image”]];

    

    UILabel *labelProductName = (UILabel *)[cell viewWithTag:101];

    labelProductName.text = [[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”name”];

    

    UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

    lblProductPrice.text = [NSString stringWithFormat:@”$%@”,[[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”price”]];

    

    

    UIButton *btnAdd = (UIButton *)[cell viewWithTag:103];

    btnAdd.tag = indexPath.row;

    [btnAdd addTarget:self action:@selector(btnAddClicked:) forControlEvents:UIControlEventTouchUpInside];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

//    self.dicProductDetailFrmProdctLst = [[NSMutableDictionary alloc]init];

//    [self.dicProductDetailFrmProdctLst setObject:@”Name” forKey:@”Philippe”];

//    [self performSegueWithIdentifier:@”cellToProductDetailViewController” sender:self.dicProductDetailFrmProdctLst];

    

}

#pragma mark – UITableViewDelegate methods

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSString *header = [[self.aryTableData objectAtIndex:section]objectForKey:@”product name”];

    return header;

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

– (IBAction)btnBackClicked:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

– (IBAction)btnCartClicked:(id)sender

{

    NSLog(@”%@”,self.arySelectedProductsFrmPrdctLst);

}

– (IBAction)btnAddClicked:(UIButton*)sender

{

    NSLog(@”%ld”,sender.tag);

    

    

//    UITableViewCell *cell = (UITableViewCell *)sender.superview;

//    NSIndexPath *indexPath = [self.tblVwRef indexPathForCell:cell];

    

    UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;

    NSIndexPath *indexPath = [self.tblVwProductList indexPathForCell:cell];

    

    UIAlertController *anAlertController = [UIAlertController alertControllerWithTitle:@”” message:@”This product has been added to the cart. Do you want to view the cart?” preferredStyle:UIAlertControllerStyleAlert];

    

    UIAlertAction *anAlertActionYes = [UIAlertAction actionWithTitle:@”YES” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSLog(@”YES”);

        

        NSLog(@”%@”,self.arySelectedProductsFrmPrdctLst);

        [self performSegueWithIdentifier:@”cartBtnToCartViewController” sender:self.arySelectedProductsFrmPrdctLst];

        

        

    }];

    [anAlertController addAction:anAlertActionYes];

    

    UIAlertAction *anAlertActionNo = [UIAlertAction actionWithTitle:@”NO” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

       

        NSLog(@”NO”);

    }];

    [anAlertController addAction:anAlertActionNo];

    

    [self presentViewController:anAlertController animated:YES completion:^{

        

        NSLog(@”Completion”);

       

        [self.arySelectedProductsFrmPrdctLst addObject:[[[self.aryTableData objectAtIndex:0]objectForKey:@”product detail”]objectAtIndex:sender.tag]];

        

        

    }];

    

}

#pragma mark – Segue

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

    NSIndexPath *indexPath = [self.tblVwProductList indexPathForSelectedRow];

    NSLog(@”%ld”,indexPath.section);

    NSLog(@”%ld”,indexPath.row);

    

    if ([segue.identifier isEqualToString:@”cellToProductDetailViewController”])

    {

        FPProductDetailViewController *prdctDtlVwct = segue.destinationViewController;

        prdctDtlVwct.dicProductDetail = [[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row];

        //[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]

    }

    

    if ([segue.identifier isEqualToString:@”cartBtnToCartViewController”])

    {

        NSLog(@”cartBtnToCartViewController”);

        

        if ([self.arySelectedProductsFrmPrdctLst count] > 0)

        {

            FPCartViewController *crtVwCt = segue.destinationViewController;

            crtVwCt.arySelectedProductsFromCart = self.arySelectedProductsFrmPrdctLst;

            

        }

        else

        {

            

            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@”Please select atleast one product” preferredStyle:UIAlertControllerStyleAlert];

            

            UIAlertAction *alrtActnOk = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

               

                NSLog(@”OK”);

                

            }];

            

            [alertController addAction:alrtActnOk];

            

            [self presentViewController:alertController animated:YES completion:^{

                

            }];

            

            

        }

        

    }

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

@end

FPCartViewController.h

#import <UIKit/UIKit.h>

@interface FPCartViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

{

    

    int productQuantity;

    float price;

    float totalPrice;

    BOOL isInOrderConfirmationView;

    

}

@property (strong, nonatomic) NSMutableArray *arySelectedProductsFromCart;

@property (weak, nonatomic) IBOutlet UITableView *tblVwSelectedProductList;

@property (weak, nonatomic) IBOutlet UIButton *btnBack;

@property (weak, nonatomic) IBOutlet UIButton *btnCheckOut;

@property (weak, nonatomic) IBOutlet UIButton *btnProceed;

@property (weak, nonatomic) IBOutlet UILabel *lblTotalPrice;

– (IBAction)btnBackClicked:(id)sender;

– (IBAction)btnCheckOutClicked:(id)sender;

– (IBAction)btnProceedClicked:(id)sender;

@end

FPCartViewController.m

#import “FPCartViewController.h”

@interface FPCartViewController ()

@end

@implementation FPCartViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    NSLog(@”%f”,[[[self.arySelectedProductsFromCart valueForKey:@”price”] objectAtIndex:0]floatValue]);

    totalPrice = 0;

    for (int i = 0; i<self.arySelectedProductsFromCart.count; i++)

    {

        totalPrice  = totalPrice + [[[self.arySelectedProductsFromCart valueForKey:@”price”] objectAtIndex:i]floatValue];

    }

    

    NSLog(@”%f”,totalPrice);

    

    self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

    

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    //isInOrderConfirmationView = NO;

    

    if (isInOrderConfirmationView == YES)

    {

        self.btnCheckOut.hidden = YES;

        self.btnProceed.hidden = NO;

        self.tblVwSelectedProductList.userInteractionEnabled = NO;

        

        

    }

    else

    {

        self.btnCheckOut.hidden = NO;

        self.btnProceed.hidden = YES;

        self.tblVwSelectedProductList.userInteractionEnabled = YES;

    }

    

    

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    

   

    

    

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

#pragma mark – UITable View Delegates

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.arySelectedProductsFromCart count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell;

    

    

    if (isInOrderConfirmationView == NO)

    {

        static NSString *cellIdentifier = @”CellNew”;

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

            

        }

        

        

        UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:100];

        UILabel *labelProductName = (UILabel *)[cell viewWithTag:101];

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

        UIButton *btnAdd = (UIButton *)[cell viewWithTag:103];

        UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

        UIButton *btnMinus = (UIButton *)[cell viewWithTag:105];

        

        imageViewProductImage.image = [UIImage imageNamed:[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”image”]];

        

        

        labelProductName.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”name”];

        

        float tempPrice;

        tempPrice = [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”price”] floatValue] * [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”] intValue];

        

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,tempPrice];

        

        

        btnAdd.hidden = NO;

        btnAdd.tag = indexPath.row;

        [btnAdd addTarget:self action:@selector(btnAddClicked:) forControlEvents:UIControlEventTouchDown];

        

        

        lblProductQuantity.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”];

        

        btnMinus.hidden = NO;

        btnMinus.tag = indexPath.row;

        [btnMinus addTarget:self action:@selector(btnMinusClicked:) forControlEvents:UIControlEventTouchDown];

    }

    else

    {

        static NSString *cellIdentifier = @”CellForOrderSummary”;

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

            

        }

        

        UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:106];

        UILabel *labelProductName = (UILabel *)[cell viewWithTag:107];

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:108];

        

        imageViewProductImage.image = [UIImage imageNamed:[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”image”]];

        labelProductName.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”name”];

        //lblProductPrice.text = [[self.arySelectedProducts objectAtIndex:indexPath.row] objectForKey:@”detail”];

        

        float tempTotalPrice = [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”price”] floatValue] * [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”] intValue];

        

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,tempTotalPrice];

    }

    

    

    

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

   

}

#pragma mark – UITableViewDelegate methods

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSString *header = @”Selected Products”;

    return header;

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 70.0;

}

– (IBAction)btnBackClicked:(id)sender

{

  //  [self.arySelectedProductsFromCart removeAllObjects];

    

    if (isInOrderConfirmationView == NO)

    {

     [self.navigationController popViewControllerAnimated:YES];

    }

    else

    {

        isInOrderConfirmationView = NO;

        self.btnProceed.hidden = YES;

        self.btnCheckOut.hidden = NO;

        self.tblVwSelectedProductList.userInteractionEnabled = YES;

        [self.tblVwSelectedProductList reloadData];

        

    }

    

    

}

– (IBAction)btnCheckOutClicked:(id)sender {

    

    

    if ([self.arySelectedProductsFromCart count] <= 0 )

    {

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@”Please select atleast one product” preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *alrtActnOk = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

            NSLog(@”OK”);

            

        }];

        

        [alertController addAction:alrtActnOk];

        

        [self presentViewController:alertController animated:YES completion:^{

            

        }];

        

    }

    else

    {

        isInOrderConfirmationView = YES;

        self.btnProceed.hidden = NO;

        self.btnCheckOut.hidden = YES;

        self.tblVwSelectedProductList.userInteractionEnabled = NO;

        [self.tblVwSelectedProductList reloadData];

    }

    

    

    

   

    

}

– (IBAction)btnProceedClicked:(id)sender

{

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

   

    

}

– (IBAction)btnAddClicked:(UIButton *)sender

{

    NSLog(@”%ld”,sender.tag);

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    productQuantity = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”productQuantity”] intValue];

    productQuantity ++;

    

    price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

    price = price * productQuantity ;

    

     NSMutableDictionary *dicCurrentSelectedProduct = [[NSMutableDictionary alloc]init];

    dicCurrentSelectedProduct = [[self.arySelectedProductsFromCart objectAtIndex:sender.tag] mutableCopy];

    [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%d”,productQuantity] forKey:@”productQuantity”];

   // [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%f”,price] forKey:@”price”];

    [self.arySelectedProductsFromCart replaceObjectAtIndex:sender.tag withObject:dicCurrentSelectedProduct];

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    

    UITableViewCell *cell;

    NSIndexPath *indexPath;

    indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:0]; // if section is 0

    cell = (UITableViewCell*)[self.tblVwSelectedProductList cellForRowAtIndexPath:indexPath];

    

    UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

    lblProductQuantity.text = [NSString stringWithFormat:@”%d”,productQuantity];

    

    UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

    lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,price];

    

    totalPrice = totalPrice + [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

    self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

    

}

– (IBAction)btnMinusClicked:(UIButton *)sender

{

    NSLog(@”%ld”,sender.tag);

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    productQuantity = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”productQuantity”] intValue];

    

    if (productQuantity == 1)

    {

    

        UIAlertController *alrtController = [UIAlertController alertControllerWithTitle:nil message:@”Do you want to remove this product from order list?” preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *alrtActnYes = [UIAlertAction actionWithTitle:@”YES” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

            price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

            totalPrice = totalPriceprice;

            

            if (totalPrice < 0)

            {

                self.lblTotalPrice.text = @”$0.00″;

            }

            else

            {

                self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

            }

            

            

            [self.arySelectedProductsFromCart removeObjectAtIndex:sender.tag];

            [self.tblVwSelectedProductList reloadData];

            

        }];

        [alrtController addAction:alrtActnYes];

        

        UIAlertAction *alrtActnNo = [UIAlertAction actionWithTitle:@”NO” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

        }];

        [alrtController addAction:alrtActnNo];

        

        [self presentViewController:alrtController animated:YES completion:^{

            

        }];

        

        

    }

    else

    {

    productQuantity –;

        

        price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

        price = price * productQuantity ;

        

        

    NSMutableDictionary *dicCurrentSelectedProduct = [[NSMutableDictionary alloc]init];

    dicCurrentSelectedProduct = [[self.arySelectedProductsFromCart objectAtIndex:sender.tag] mutableCopy];

    [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%d”,productQuantity] forKey:@”productQuantity”];

    [self.arySelectedProductsFromCart replaceObjectAtIndex:sender.tag withObject:dicCurrentSelectedProduct];

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    NSIndexPath *indexPath;

    UITableViewCell *cell;

    indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:0]; // if section is 0

    cell = (UITableViewCell*)[self.tblVwSelectedProductList cellForRowAtIndexPath:indexPath];

    UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

    lblProductQuantity.text = [NSString stringWithFormat:@”%d”,productQuantity];

        

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,price];

        

        totalPrice = totalPrice – [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

        self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

        

    }

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

@end

Download Sample Project From Github

KLCPopup with Library

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIPopoverControllerDelegate, UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate>

@end

ViewController.m

#import “ViewController.h”

#import “KLCPopup.h”

#import <QuartzCore/QuartzCore.h>

typedef NS_ENUM(NSInteger, FieldTag) {

  FieldTagHorizontalLayout = 1001,

  FieldTagVerticalLayout,

  FieldTagMaskType,

  FieldTagShowType,

  FieldTagDismissType,

  FieldTagBackgroundDismiss,

  FieldTagContentDismiss,

  FieldTagTimedDismiss,

};

typedef NS_ENUM(NSInteger, CellType) {

  CellTypeNormal = 0,

  CellTypeSwitch,

};

@interface ViewController () {

  

  NSArray* _fields;

  NSDictionary* _namesForFields;

  

  NSArray* _horizontalLayouts;

  NSArray* _verticalLayouts;

  NSArray* _maskTypes;

  NSArray* _showTypes;

  NSArray* _dismissTypes;

  

  NSDictionary* _namesForHorizontalLayouts;

  NSDictionary* _namesForVerticalLayouts;

  NSDictionary* _namesForMaskTypes;

  NSDictionary* _namesForShowTypes;

  NSDictionary* _namesForDismissTypes;

  

  NSInteger _selectedRowInHorizontalField;

  NSInteger _selectedRowInVerticalField;

  NSInteger _selectedRowInMaskField;

  NSInteger _selectedRowInShowField;

  NSInteger _selectedRowInDismissField;

  BOOL _shouldDismissOnBackgroundTouch;

  BOOL _shouldDismissOnContentTouch;

  BOOL _shouldDismissAfterDelay;

}

@property (nonatomic, strong) UITableView* tableView;

@property (nonatomic, strong) UIPopoverController* popover;

// Private

– (void)updateFieldTableView:(UITableView*)tableView;

– (NSInteger)valueForRow:(NSInteger)row inFieldWithTag:(NSInteger)tag;

– (NSInteger)selectedRowForFieldWithTag:(NSInteger)tag;

– (NSString*)nameForValue:(NSInteger)value inFieldWithTag:(NSInteger)tag;

– (CellType)cellTypeForFieldWithTag:(NSInteger)tag;

// Event handlers

– (void)toggleValueDidChange:(id)sender;

– (void)showButtonPressed:(id)sender;

– (void)dismissButtonPressed:(id)sender;

– (void)fieldCancelButtonPressed:(id)sender;

@end

@interface UIColor (KLCPopupExample)

+ (UIColor*)klcLightGreenColor;

+ (UIColor*)klcGreenColor;

@end

@interface UIView (KLCPopupExample)

– (UITableViewCell*)parentCell;

@end

@implementation ViewController

#pragma mark – UIViewController

– (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

  if (self) {

    

    self.title = @”KLCPopup Example”;

    

    // MAIN LIST

    _fields = @[@(FieldTagHorizontalLayout),

                @(FieldTagVerticalLayout),

                @(FieldTagMaskType),

                @(FieldTagShowType),

                @(FieldTagDismissType),

                @(FieldTagBackgroundDismiss),

                @(FieldTagContentDismiss),

                @(FieldTagTimedDismiss)];

    

    _namesForFields = @{@(FieldTagHorizontalLayout) : @”Horizontal layout”,

                        @(FieldTagVerticalLayout) : @”Vertical layout”,

                        @(FieldTagMaskType) : @”Background mask”,

                        @(FieldTagShowType) : @”Show type”,

                        @(FieldTagDismissType) : @”Dismiss type”,

                        @(FieldTagBackgroundDismiss) : @”Dismiss on background touch”,

                        @(FieldTagContentDismiss) : @”Dismiss on content touch”,

                        @(FieldTagTimedDismiss) : @”Dismiss after delay”};

    

    // FIELD SUB-LISTS

    _horizontalLayouts = @[@(KLCPopupHorizontalLayoutLeft),

                           @(KLCPopupHorizontalLayoutLeftOfCenter),

                           @(KLCPopupHorizontalLayoutCenter),

                           @(KLCPopupHorizontalLayoutRightOfCenter),

                           @(KLCPopupHorizontalLayoutRight)];

    

    _namesForHorizontalLayouts = @{@(KLCPopupHorizontalLayoutLeft) : @”Left”,

                                   @(KLCPopupHorizontalLayoutLeftOfCenter) : @”Left of Center”,

                                   @(KLCPopupHorizontalLayoutCenter) : @”Center”,

                                   @(KLCPopupHorizontalLayoutRightOfCenter) : @”Right of Center”,

                                   @(KLCPopupHorizontalLayoutRight) : @”Right”};

    

    _verticalLayouts = @[@(KLCPopupVerticalLayoutTop),

                         @(KLCPopupVerticalLayoutAboveCenter),

                         @(KLCPopupVerticalLayoutCenter),

                         @(KLCPopupVerticalLayoutBelowCenter),

                         @(KLCPopupVerticalLayoutBottom)];

    

    _namesForVerticalLayouts = @{@(KLCPopupVerticalLayoutTop) : @”Top”,

                                 @(KLCPopupVerticalLayoutAboveCenter) : @”Above Center”,

                                 @(KLCPopupVerticalLayoutCenter) : @”Center”,

                                 @(KLCPopupVerticalLayoutBelowCenter) : @”Below Center”,

                                 @(KLCPopupVerticalLayoutBottom) : @”Bottom”};

    

    _maskTypes = @[@(KLCPopupMaskTypeNone),

                   @(KLCPopupMaskTypeClear),

                   @(KLCPopupMaskTypeDimmed)];

    

    _namesForMaskTypes = @{@(KLCPopupMaskTypeNone) : @”None”,

                           @(KLCPopupMaskTypeClear) : @”Clear”,

                           @(KLCPopupMaskTypeDimmed) : @”Dimmed”};

    

    _showTypes = @[@(KLCPopupShowTypeNone),

                   @(KLCPopupShowTypeFadeIn),

                   @(KLCPopupShowTypeGrowIn),

                   @(KLCPopupShowTypeShrinkIn),

                   @(KLCPopupShowTypeSlideInFromTop),

                   @(KLCPopupShowTypeSlideInFromBottom),

                   @(KLCPopupShowTypeSlideInFromLeft),

                   @(KLCPopupShowTypeSlideInFromRight),

                   @(KLCPopupShowTypeBounceIn),

                   @(KLCPopupShowTypeBounceInFromTop),

                   @(KLCPopupShowTypeBounceInFromBottom),

                   @(KLCPopupShowTypeBounceInFromLeft),

                   @(KLCPopupShowTypeBounceInFromRight)];

    

    _namesForShowTypes = @{@(KLCPopupShowTypeNone) : @”None”,

                           @(KLCPopupShowTypeFadeIn) : @”Fade in”,

                           @(KLCPopupShowTypeGrowIn) : @”Grow in”,

                           @(KLCPopupShowTypeShrinkIn) : @”Shrink in”,

                           @(KLCPopupShowTypeSlideInFromTop) : @”Slide from Top”,

                           @(KLCPopupShowTypeSlideInFromBottom) : @”Slide from Bottom”,

                           @(KLCPopupShowTypeSlideInFromLeft) : @”Slide from Left”,

                           @(KLCPopupShowTypeSlideInFromRight) : @”Slide from Right”,

                           @(KLCPopupShowTypeBounceIn) : @”Bounce in”,

                           @(KLCPopupShowTypeBounceInFromTop) : @”Bounce from Top”,

                           @(KLCPopupShowTypeBounceInFromBottom) : @”Bounce from Bottom”,

                           @(KLCPopupShowTypeBounceInFromLeft) : @”Bounce from Left”,

                           @(KLCPopupShowTypeBounceInFromRight) : @”Bounce from Right”};

    

    _dismissTypes = @[@(KLCPopupDismissTypeNone),

                      @(KLCPopupDismissTypeFadeOut),

                      @(KLCPopupDismissTypeGrowOut),

                      @(KLCPopupDismissTypeShrinkOut),

                      @(KLCPopupDismissTypeSlideOutToTop),

                      @(KLCPopupDismissTypeSlideOutToBottom),

                      @(KLCPopupDismissTypeSlideOutToLeft),

                      @(KLCPopupDismissTypeSlideOutToRight),

                      @(KLCPopupDismissTypeBounceOut),

                      @(KLCPopupDismissTypeBounceOutToTop),

                      @(KLCPopupDismissTypeBounceOutToBottom),

                      @(KLCPopupDismissTypeBounceOutToLeft),

                      @(KLCPopupDismissTypeBounceOutToRight)];

    

    _namesForDismissTypes = @{@(KLCPopupDismissTypeNone) : @”None”,

                              @(KLCPopupDismissTypeFadeOut) : @”Fade out”,

                              @(KLCPopupDismissTypeGrowOut) : @”Grow out”,

                              @(KLCPopupDismissTypeShrinkOut) : @”Shrink out”,

                              @(KLCPopupDismissTypeSlideOutToTop) : @”Slide to Top”,

                              @(KLCPopupDismissTypeSlideOutToBottom) : @”Slide to Bottom”,

                              @(KLCPopupDismissTypeSlideOutToLeft) : @”Slide to Left”,

                              @(KLCPopupDismissTypeSlideOutToRight) : @”Slide to Right”,

                              @(KLCPopupDismissTypeBounceOut) : @”Bounce out”,

                              @(KLCPopupDismissTypeBounceOutToTop) : @”Bounce to Top”,

                              @(KLCPopupDismissTypeBounceOutToBottom) : @”Bounce to Bottom”,

                              @(KLCPopupDismissTypeBounceOutToLeft) : @”Bounce to Left”,

                              @(KLCPopupDismissTypeBounceOutToRight) : @”Bounce to Right”};

    

    // DEFAULTS

    _selectedRowInHorizontalField = [_horizontalLayouts indexOfObject:@(KLCPopupHorizontalLayoutCenter)];

    _selectedRowInVerticalField = [_verticalLayouts indexOfObject:@(KLCPopupVerticalLayoutCenter)];

    _selectedRowInMaskField = [_maskTypes indexOfObject:@(KLCPopupMaskTypeDimmed)];

    _selectedRowInShowField = [_showTypes indexOfObject:@(KLCPopupShowTypeBounceInFromTop)];

    _selectedRowInDismissField = [_dismissTypes indexOfObject:@(KLCPopupDismissTypeBounceOutToBottom)];

    _shouldDismissOnBackgroundTouch = YES;

    _shouldDismissOnContentTouch = NO;

    _shouldDismissAfterDelay = NO;

  }

  return self;

}

– (void)loadView {

  [super loadView];

  

  // TABLEVIEW

  UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];

  tableView.translatesAutoresizingMaskIntoConstraints = NO;

  tableView.delegate = self;

  tableView.dataSource = self;

  tableView.delaysContentTouches = NO;

  self.tableView = tableView;

  [self.view addSubview:tableView];

  

  NSDictionary* views = NSDictionaryOfVariableBindings(tableView);

  NSDictionary* metrics = nil;

  [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@”H:|[tableView]|”

                                                                    options:0

                                                                    metrics:metrics

                                                                      views:views]];

  

  [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@”V:|[tableView]|”

                                                                    options:0

                                                                    metrics:metrics

                                                                      views:views]];

  

  // FOOTER

  UIView* footerView = [[UIView alloc] init];

  

  UIButton* showButton = [UIButton buttonWithType:UIButtonTypeCustom];

  showButton.translatesAutoresizingMaskIntoConstraints = NO;

  showButton.contentEdgeInsets = UIEdgeInsetsMake(14, 28, 14, 28);

  [showButton setTitle:@”Show it!” forState:UIControlStateNormal];

  showButton.backgroundColor = [UIColor lightGrayColor];

  [showButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

  [showButton setTitleColor:[[showButton titleColorForState:UIControlStateNormal] colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];

  showButton.titleLabel.font = [UIFont boldSystemFontOfSize:20.0];

  [showButton.layer setCornerRadius:8.0];

  [showButton addTarget:self action:@selector(showButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

  

  [footerView addSubview:showButton];

  

  CGFloat topMargin = 12.0;

  CGFloat bottomMargin = 12.0;

  

  views = NSDictionaryOfVariableBindings(showButton);

  metrics = @{@”topMargin” : @(topMargin),

              @”bottomMargin” : @(bottomMargin)};

  [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@”V:|-(topMargin)-[showButton]-(bottomMargin)-|”

                                                                     options:0

                                                                     metrics:metrics

                                                                       views:views]];

  

  [footerView addConstraint:[NSLayoutConstraint constraintWithItem:showButton

                                                         attribute:NSLayoutAttributeCenterX

                                                         relatedBy:NSLayoutRelationEqual

                                                            toItem:showButton.superview

                                                         attribute:NSLayoutAttributeCenterX

                                                        multiplier:1.0

                                                          constant:0.0]];

  

  CGRect footerFrame = CGRectZero;

  footerFrame.size = [showButton systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

  footerFrame.size.height += topMargin + bottomMargin;

  footerView.frame = footerFrame;

  self.tableView.tableFooterView = footerView;

}

– (void)viewDidLoad

{

  [super viewDidLoad];

  

  self.automaticallyAdjustsScrollViewInsets = YES;

  self.view.backgroundColor = [UIColor whiteColor];

}

#pragma mark – Event Handlers

– (void)toggleValueDidChange:(id)sender {

  

  if ([sender isKindOfClass:[UISwitch class]]) {

    UISwitch* toggle = (UISwitch*)sender;

    

    NSIndexPath* indexPath = [self.tableView indexPathForCell:[toggle parentCell]];

    id obj = [_fields objectAtIndex:indexPath.row];

    if ([obj isKindOfClass:[NSNumber class]]) {

      

      NSInteger fieldTag = [(NSNumber*)obj integerValue];

      if (fieldTag == FieldTagBackgroundDismiss) {

        _shouldDismissOnBackgroundTouch = toggle.on;

        

      } else if (fieldTag == FieldTagContentDismiss) {

        _shouldDismissOnContentTouch = toggle.on;

        

      } else if (fieldTag == FieldTagTimedDismiss) {

        _shouldDismissAfterDelay = toggle.on;

      }

    }

  }

}

– (void)showButtonPressed:(id)sender {

  

  // Generate content view to present

  UIView* contentView = [[UIView alloc] init];

  contentView.translatesAutoresizingMaskIntoConstraints = NO;

  contentView.backgroundColor = [UIColor klcLightGreenColor];

  contentView.layer.cornerRadius = 12.0;

  

  UILabel* dismissLabel = [[UILabel alloc] init];

  dismissLabel.translatesAutoresizingMaskIntoConstraints = NO;

  dismissLabel.backgroundColor = [UIColor clearColor];

  dismissLabel.textColor = [UIColor whiteColor];

  dismissLabel.font = [UIFont boldSystemFontOfSize:72.0];

  dismissLabel.text = @”Hi.”;

  

  UIButton* dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];

  dismissButton.translatesAutoresizingMaskIntoConstraints = NO;

  dismissButton.contentEdgeInsets = UIEdgeInsetsMake(10, 20, 10, 20);

  dismissButton.backgroundColor = [UIColor klcGreenColor];

  [dismissButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

  [dismissButton setTitleColor:[[dismissButton titleColorForState:UIControlStateNormal] colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];

  dismissButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0];

  [dismissButton setTitle:@”Bye” forState:UIControlStateNormal];

  dismissButton.layer.cornerRadius = 6.0;

  [dismissButton addTarget:self action:@selector(dismissButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

  

  [contentView addSubview:dismissLabel];

  [contentView addSubview:dismissButton];

  

  NSDictionary* views = NSDictionaryOfVariableBindings(contentView, dismissButton, dismissLabel);

  

  [contentView addConstraints:

   [NSLayoutConstraint constraintsWithVisualFormat:@”V:|-(16)-[dismissLabel]-(10)-[dismissButton]-(24)-|”

                                           options:NSLayoutFormatAlignAllCenterX

                                           metrics:nil

                                             views:views]];

  

  [contentView addConstraints:

   [NSLayoutConstraint constraintsWithVisualFormat:@”H:|-(36)-[dismissLabel]-(36)-|”

                                           options:0

                                           metrics:nil

                                             views:views]];

  

  // Show in popup

  KLCPopupLayout layout = KLCPopupLayoutMake((KLCPopupHorizontalLayout)[self valueForRow:_selectedRowInHorizontalField inFieldWithTag:FieldTagHorizontalLayout],

                                             (KLCPopupVerticalLayout)[self valueForRow:_selectedRowInVerticalField inFieldWithTag:FieldTagVerticalLayout]);

  

  KLCPopup* popup = [KLCPopup popupWithContentView:contentView

                                          showType:(KLCPopupShowType)[self valueForRow:_selectedRowInShowField inFieldWithTag:FieldTagShowType]

                                       dismissType:(KLCPopupDismissType)[self valueForRow:_selectedRowInDismissField inFieldWithTag:FieldTagDismissType]

                                          maskType:(KLCPopupMaskType)[self valueForRow:_selectedRowInMaskField inFieldWithTag:FieldTagMaskType]

                          dismissOnBackgroundTouch:_shouldDismissOnBackgroundTouch

                             dismissOnContentTouch:_shouldDismissOnContentTouch];

  

  if (_shouldDismissAfterDelay) {

    [popup showWithLayout:layout duration:2.0];

  } else {

    [popup showWithLayout:layout];

  }

}

– (void)dismissButtonPressed:(id)sender {

  if ([sender isKindOfClass:[UIView class]]) {

    [(UIView*)sender dismissPresentingPopup];

  }

}

– (void)fieldCancelButtonPressed:(id)sender {

  [self dismissViewControllerAnimated:YES completion:NULL];

}

#pragma mark – Private

– (void)updateFieldTableView:(UITableView*)tableView {

  

  if (tableView != nil) {

    

    NSInteger fieldTag = tableView.tag;

    NSInteger selectedRow = [self selectedRowForFieldWithTag:fieldTag];

    

    for (NSIndexPath* indexPath in [tableView indexPathsForVisibleRows]) {

      

      UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

      if (cell != nil) {

        

        if (indexPath.row == selectedRow) {

          cell.accessoryType = UITableViewCellAccessoryCheckmark;

        } else {

          cell.accessoryType = UITableViewCellAccessoryNone;

        }

      }

    }

  }

}

– (NSInteger)valueForRow:(NSInteger)row inFieldWithTag:(NSInteger)tag {

  

  NSArray* listForField = nil;

  if (tag == FieldTagHorizontalLayout) {

    listForField = _horizontalLayouts;

    

  } else if (tag == FieldTagVerticalLayout) {

    listForField = _verticalLayouts;

    

  } else if (tag == FieldTagMaskType) {

    listForField = _maskTypes;

    

  } else if (tag == FieldTagShowType) {

    listForField = _showTypes;

    

  } else if (tag == FieldTagDismissType) {

    listForField = _dismissTypes;

  }

  

  // If row is out of bounds, try using first row.

  if (row >= listForField.count) {

    row = 0;

  }

  

  if (row < listForField.count) {

    id obj = [listForField objectAtIndex:row];

    if ([obj isKindOfClass:[NSNumber class]]) {

      return [(NSNumber*)obj integerValue];

    }

  }

  

  return 0;

}

– (NSInteger)selectedRowForFieldWithTag:(NSInteger)tag {

  if (tag == FieldTagHorizontalLayout) {

    return _selectedRowInHorizontalField;

    

  } else if (tag == FieldTagVerticalLayout) {

    return _selectedRowInVerticalField;

    

  } else if (tag == FieldTagMaskType) {

    return _selectedRowInMaskField;

    

  } else if (tag == FieldTagShowType) {

    return _selectedRowInShowField;

    

  } else if (tag == FieldTagDismissType) {

    return _selectedRowInDismissField;

  }

  return NSNotFound;

}

– (NSString*)nameForValue:(NSInteger)value inFieldWithTag:(NSInteger)tag {

  

  NSDictionary* namesForField = nil;

  if (tag == FieldTagHorizontalLayout) {

    namesForField = _namesForHorizontalLayouts;

    

  } else if (tag == FieldTagVerticalLayout) {

    namesForField = _namesForVerticalLayouts;

    

  } else if (tag == FieldTagMaskType) {

    namesForField = _namesForMaskTypes;

    

  } else if (tag == FieldTagShowType) {

    namesForField = _namesForShowTypes;

    

  } else if (tag == FieldTagDismissType) {

    namesForField = _namesForDismissTypes;

  }

  

  if (namesForField != nil) {

    return [namesForField objectForKey:@(value)];

  }

  return nil;

}

– (CellType)cellTypeForFieldWithTag:(NSInteger)tag {

  

  CellType cellType;

  switch (tag) {

    case FieldTagHorizontalLayout:

      cellType = CellTypeNormal;

      break;

    case FieldTagVerticalLayout:

      cellType = CellTypeNormal;

      break;

    case FieldTagMaskType:

      cellType = CellTypeNormal;

      break;

    case FieldTagShowType:

      cellType = CellTypeNormal;

      break;

    case FieldTagDismissType:

      cellType = CellTypeNormal;

      break;

    case FieldTagBackgroundDismiss:

      cellType = CellTypeSwitch;

      break;

    case FieldTagContentDismiss:

      cellType = CellTypeSwitch;

      break;

    case FieldTagTimedDismiss:

      cellType = CellTypeSwitch;

      break;

    default:

      cellType = CellTypeNormal;

      break;

  }

  return cellType;

}

#pragma mark – <UITableViewDataSource>

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

  

  // MAIN TABLE

  if (tableView == self.tableView) {

    return _fields.count;

  }

  

  // FIELD TABLES

  else {

    

    if (tableView.tag == FieldTagHorizontalLayout) {

      return _horizontalLayouts.count;

      

    } else if (tableView.tag == FieldTagVerticalLayout) {

      return _verticalLayouts.count;

      

    } else if (tableView.tag == FieldTagMaskType) {

      return _maskTypes.count;

      

    } else if (tableView.tag == FieldTagShowType) {

      return _showTypes.count;

      

    } else if (tableView.tag == FieldTagDismissType) {

      return _dismissTypes.count;

    }

  }

  

  return 0;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  

  // MAIN TABLE

  if (tableView == self.tableView) {

    

    id obj = [_fields objectAtIndex:indexPath.row];

    if ([obj isKindOfClass:[NSNumber class]]) {

      FieldTag fieldTag = [(NSNumber*)obj integerValue];

      

      UITableViewCell* cell = nil;

      CellType cellType = [self cellTypeForFieldWithTag:fieldTag];

      

      NSString* identifier = @””;

      if (cellType == CellTypeNormal) {

        identifier = @”normal”;

      } else if (cellType == CellTypeSwitch) {

        identifier = @”switch”;

      }

      

      cell = [tableView dequeueReusableCellWithIdentifier:identifier];

      

      if (nil == cell) {

        UITableViewCellStyle style = UITableViewCellStyleValue1;

        cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:identifier];

        UIEdgeInsets newSeparatorInset = cell.separatorInset;

        newSeparatorInset.right = newSeparatorInset.left;

        cell.separatorInset = newSeparatorInset;

        

        if (cellType == CellTypeNormal) {

          cell.selectionStyle = UITableViewCellSelectionStyleGray;

          

        } else if (cellType == CellTypeSwitch) {

          cell.selectionStyle = UITableViewCellSelectionStyleNone;

          UISwitch* toggle = [[UISwitch alloc] init];

          toggle.onTintColor = [UIColor lightGrayColor];

          [toggle addTarget:self action:@selector(toggleValueDidChange:) forControlEvents:UIControlEventValueChanged];

          cell.accessoryView = toggle;

        }

      }

      

      cell.textLabel.text = [_namesForFields objectForKey:@(fieldTag)];

      

      // populate Normal cell

      if (cellType == CellTypeNormal) {

        NSInteger selectedRowInField = [self selectedRowForFieldWithTag:fieldTag];

        if (selectedRowInField != NSNotFound) {

          cell.detailTextLabel.text = [self nameForValue:[self valueForRow:selectedRowInField inFieldWithTag:fieldTag] inFieldWithTag:fieldTag];

        }

      }

      // populate Switch cell

      else if (cellType == CellTypeSwitch) {

        if ([cell.accessoryView isKindOfClass:[UISwitch class]]) {

          BOOL on = NO;

          if (fieldTag == FieldTagBackgroundDismiss) {

            on = _shouldDismissOnBackgroundTouch;

          } else if (fieldTag == FieldTagContentDismiss) {

            on = _shouldDismissOnContentTouch;

          } else if (fieldTag == FieldTagTimedDismiss) {

            on = _shouldDismissAfterDelay;

          }

          [(UISwitch*)cell.accessoryView setOn:on];

        }

      }

      

      return cell;

    }

  }

  

  // FIELD TABLES

  else {

    

    UITableViewCell* cell = nil;

    

    Class cellClass = [UITableViewCell class];

    NSString* identifier = NSStringFromClass(cellClass);

    

    cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    

    if (nil == cell) {

      UITableViewCellStyle style = UITableViewCellStyleDefault;

      cell = [[cellClass alloc] initWithStyle:style reuseIdentifier:identifier];

      UIEdgeInsets newSeparatorInset = cell.separatorInset;

      newSeparatorInset.right = newSeparatorInset.left;

      cell.separatorInset = newSeparatorInset;

    }

    

    NSInteger fieldTag = tableView.tag;

    

    cell.textLabel.text = [self nameForValue:[self valueForRow:indexPath.row inFieldWithTag:fieldTag] inFieldWithTag:fieldTag];

    

    if (indexPath.row == [self selectedRowForFieldWithTag:fieldTag]) {

      cell.accessoryType = UITableViewCellAccessoryCheckmark;

    } else {

      cell.accessoryType = UITableViewCellAccessoryNone;

    }

    

    return cell;

  }

  

  return nil;

}

#pragma mark – <UITableViewDelegate>

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  

  // MAIN TABLE

  if (tableView == self.tableView) {

    

    id obj = [_fields objectAtIndex:indexPath.row];

    if ([obj isKindOfClass:[NSNumber class]]) {

      NSInteger fieldTag = [(NSNumber*)obj integerValue];

      

      if ([self cellTypeForFieldWithTag:fieldTag] == CellTypeNormal) {

        

        UIViewController* fieldController = [[UIViewController alloc] init];

        

        UITableView* fieldTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];

        fieldTableView.delegate = self;

        fieldTableView.dataSource = self;

        fieldTableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

        fieldTableView.tag = fieldTag;

        fieldController.view = fieldTableView;

        

        // IPAD

        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {

          

          // Present in a popover

          UIPopoverController* popover = [[UIPopoverController alloc] initWithContentViewController:fieldController];

          popover.delegate = self;

          self.popover = popover;

          

          // Set KVO so we can adjust the popover’s size to fit the table’s content once it’s populated.

          [fieldTableView addObserver:self forKeyPath:@”contentSize” options:NSKeyValueObservingOptionNew context:nil];

          

          CGRect senderFrameInView = [self.tableView convertRect:[self.tableView rectForRowAtIndexPath:indexPath] toView:self.view];

          [popover presentPopoverFromRect:senderFrameInView inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

        }

        

        // IPHONE

        else {

          

          // Present in a modal

          UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

          fieldController.title = cell.textLabel.text;

          UIBarButtonItem* cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(fieldCancelButtonPressed:)];

          fieldController.navigationItem.rightBarButtonItem = cancelButton;

          

          UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:fieldController];

          navigationController.delegate = self;

          [self presentViewController:navigationController animated:YES completion:NULL];

        }

      }

    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

  }

  

  // FIELD TABLES

  else {

    

    if (tableView.tag == FieldTagHorizontalLayout) {

      _selectedRowInHorizontalField = indexPath.row;

      

    } else if (tableView.tag == FieldTagVerticalLayout) {

      _selectedRowInVerticalField = indexPath.row;

      

    } else if (tableView.tag == FieldTagMaskType) {

      _selectedRowInMaskField = indexPath.row;

      

    } else if (tableView.tag == FieldTagShowType) {

      _selectedRowInShowField = indexPath.row;

      

    } else if (tableView.tag == FieldTagDismissType) {

      _selectedRowInDismissField = indexPath.row;

    }

    

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    

    [self updateFieldTableView:tableView];

    

    [self.tableView reloadData];

    

    // IPAD

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {

      [self.popover dismissPopoverAnimated:YES];

    }

    // IPHONE

    else {

      [self dismissViewControllerAnimated:YES completion:NULL];

    }

  }

}

#pragma mark – <UINavigationControllerDelegate>

– (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

  

  // If this is a field table, make sure the selected row is scrolled into view when it appears.

  if ((navigationController == self.presentedViewController) && [viewController.view isKindOfClass:[UITableView class]]) {

    

    UITableView* fieldTableView = (UITableView*)viewController.view;

    

    NSInteger selectedRow = [self selectedRowForFieldWithTag:fieldTableView.tag];

    if ([fieldTableView numberOfRowsInSection:0] > selectedRow) {

      [fieldTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

    }

  }

}

#pragma mark – <UIPopoverControllerDelegate>

– (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {

  

  // Cleanup by removing KVO and reference to popover

  UIView* view = popoverController.contentViewController.view;

  if ([view isKindOfClass:[UITableView class]]) {

    [(UITableView*)view removeObserver:self forKeyPath:@”contentSize”];

  }

  

  self.popover = nil;

}

#pragma mark – <NSKeyValueObserving>

– (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

  

  if ([keyPath isEqualToString:@”contentSize”]) {

    

    if ([object isKindOfClass:[UITableView class]]) {

      UITableView* tableView = (UITableView*)object;

      

      if (self.popover != nil) {

        [self.popover setPopoverContentSize:tableView.contentSize animated:NO];

      }

      

      // Make sure the selected row is scrolled into view when it appears

      NSInteger fieldTag = tableView.tag;

      NSInteger selectedRow = [self selectedRowForFieldWithTag:fieldTag];

      

      if ([tableView numberOfRowsInSection:0] > selectedRow) {

        [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

      }

    }

  }

}

@end

#pragma mark – Categories

@implementation UIColor (KLCPopupExample)

+ (UIColor*)klcLightGreenColor {

  return [UIColor colorWithRed:(184.0/255.0) green:(233.0/255.0) blue:(122.0/255.0) alpha:1.0];

}

+ (UIColor*)klcGreenColor {

  return [UIColor colorWithRed:(0.0/255.0) green:(204.0/255.0) blue:(134.0/255.0) alpha:1.0];

}

@end

@implementation UIView (KLCPopupExample)

– (UITableViewCell*)parentCell {

  

  // Iterate over superviews until you find a UITableViewCell

  UIView* view = self;

  while (view != nil) {

    if ([view isKindOfClass:[UITableViewCell class]]) {

      return (UITableViewCell*)view;

    } else {

      view = [view superview];

    }

  }

  return nil;

}

@end

Download Sample Project And KLCPopup Library From Github

Json Get From File

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

   

    

    //NSLog(@”%@”,[Utility parseStatesResponseFileName:@”Login_Json_File” FileType:@”json”]);

    self.arrayLogin = [Utility parseStatesResponseFileName:@”Login_Json_File” FileType:@”json”];

    NSLog(@”%@”,self.arrayLogin);

    

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+ (NSArray *)parseStatesResponseFileName:(NSString *)aFileName FileType:(NSString *)aFileType;

@end

Utility.m

#import “Utility.h”

@implementation Utility

+ (NSArray *)parseStatesResponseFileName:(NSString *)aFileName FileType:(NSString *)aFileType

{

    NSString *aFilePath = [[NSBundle mainBundle] pathForResource:aFileName ofType:aFileType];

    NSString *aJsonContent = [NSString stringWithContentsOfFile:aFilePath encoding:NSUTF8StringEncoding error:nil];

    NSData *aData = [aJsonContent dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];;;

    NSError *anError;

    NSArray *arrayJson = [NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&anError];

    //    NSLog(@”%@”,arrayJson);

    return arrayJson;

}

@end

Download Sample Project From Github

Json Parsing Sample Project

ViewController.h

#import <UIKit/UIKit.h>

#import “VendorListParser.h”

#import “VendorListViewController.h”

@interface ViewController : UIViewController

– (IBAction)btn1:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    // Do any additional setup after loading the view from its nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)btn1:(id)sender {

    

    

    VendorListParser *aListParser = [[VendorListParser alloc] init];

    

    [aListParser getVendorsList:^(NSMutableArray *vendorsList) {

        VendorListViewController *vndrlst=[[VendorListViewController alloc]initWithNibName:@”VendorListViewController” bundle:nil];

        vndrlst.vendorsList = vendorsList;

        [self.navigationController pushViewController:vndrlst animated:YES];

    } withFailureBlock:^(NSString *errorMessage) {

        UIAlertController *anAlertController = [UIAlertController alertControllerWithTitle:@”” message:errorMessage preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *anAction = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

        }];

        [anAlertController addAction:anAction];

        [self presentViewController:anAlertController animated:YES completion:^{

            

        }];

    }];

}

@end

VendorListViewController.h

#import <UIKit/UIKit.h>

#import “Vendor.h”

@interface VendorListViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>

{

    NSMutableArray *_myCollectionArray;

   

}

@property (strong, nonatomic) IBOutlet UICollectionView *collectionView1;

@property (nonatomic, retain) NSMutableArray *vendorsList;

//@property (nonatomic, strong) NSArray *dataArray;

– (IBAction)clsbtnactn:(id)sender;

@end

VendorListViewController.m

#import “VendorListViewController.h”

#import “NibCell.h”

@interface VendorListViewController ()

@end

@implementation VendorListViewController

@synthesize collectionView1;

– (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@”bg image”]];

    collectionView1.backgroundColor = [UIColor colorWithWhite:0 alpha:0];

    

    self.navigationController.navigationBarHidden=YES;

//    NSMutableArray *firstSection = [[NSMutableArray alloc] init]; NSMutableArray *secondSection = [[NSMutableArray alloc] init];

//    for (int i=0; i<50; i++) {

//        [firstSection addObject:[NSString stringWithFormat:@”Cell %d”, i]];

//        [secondSection addObject:[NSString stringWithFormat:@”item %d”, i]];

//    }

//    self.dataArray = [[NSArray alloc] initWithObjects:firstSection, secondSection, nil];

//    

    

    UINib *cellNib = [UINib nibWithNibName:@”NibCell” bundle:nil];

    [self.collectionView1 registerNib:cellNib forCellWithReuseIdentifier:@”cvCell”];

    

    

    

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(160, 270)];

    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

    

    [self.collectionView1 setCollectionViewLayout:flowLayout];

  //  collectionView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@”bg image”]];

    

    // Do any additional setup after loading the view from its nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

   // return [self.dataArray count];

    return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

  //  NSMutableArray *sectionArray = [self.dataArray objectAtIndex:section];

   // return [sectionArray count];

    return [self.vendorsList count];

}

-(NibCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    

//    NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];

    

//    NSString *cellData = [data objectAtIndex:0];

    

    static NSString *cellIdentifier = @”cvCell”;

    

    NibCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    NSLog(@”%ld”,(long)indexPath.row);

    cell.callimgvw.tag = (long)indexPath.item;

    Vendor *aVendor = [self.vendorsList objectAtIndex:indexPath.item];

    cell.lbl2.text = aVendor.vendorName;

    cell.lbl3.text = [self convertHTML:aVendor.vendorDesc];

    cell.lbl1.text = [NSString stringWithFormat:@”$%0.2f”,aVendor.price];

    

    NSLog(@”%@”,[self convertHTML:aVendor.vendorDesc]);

    

    if (aVendor.vendorLogo.length > 0) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            NSURL *aUrl = [NSURL URLWithString:aVendor.vendorLogo];

           UIImage *aImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:aUrl]];

            dispatch_async(dispatch_get_main_queue(), ^{

                cell.imgvw.image = aImage;

            });

        });

    }

    

    return cell;

    

}

#pragma mark collection view cell paddings

– (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {

    return UIEdgeInsetsMake(10, 20, 10, 20); // top, left, bottom, right

}

– (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {

    return 0.5;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”%ld”,(long)indexPath.row);

    

    

//    NibCell *cell = (NibCell*)[collectionView cellForItemAtIndexPath:indexPath];

//    NSArray *views = [cell.contentView subviews];

//    UIButton *label = [views objectAtIndex:0];

//    NSLog(@”Select %ld”,(long)label.tag);

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)clsbtnactn:(id)sender

{

    [self.navigationController popToRootViewControllerAnimated:YES];

    

}

-(NSString *)convertHTML:(NSString *)html {

    

    NSScanner *myScanner;

    NSString *text = nil;

    myScanner = [NSScanner scannerWithString:html];

    

    while ([myScanner isAtEnd] == NO) {

        

        [myScanner scanUpToString:@”<“ intoString:NULL] ;

        

        [myScanner scanUpToString:@”>” intoString:&text] ;

        

        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@”%@>”, text] withString:@””];

    }

    //

    html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    

    return html;

}

@end

NibCell.h

#import <UIKit/UIKit.h>

//@protocol CellDelegate <NSObject>

//

//- (void)didClickOnCellAtIndex:(NSInteger)cellIndex withData:(id)data;

//

//@end

@interface NibCell : UICollectionViewCell

@property (strong, nonatomic) IBOutlet UIImageView *callimgvw;

@property (strong, nonatomic) IBOutlet UIImageView *imgvw;

@property (strong, nonatomic) IBOutlet UILabel *lbl1;

@property (strong, nonatomic) IBOutlet UILabel *lbl2;

@property (strong, nonatomic) IBOutlet UILabel *lbl3;

//@property (weak, nonatomic) id<CellDelegate>delegate;

//@property (assign, nonatomic) NSInteger cellIndex;

– (IBAction)pressButton:(id)sender;

@end

NibCell.m

#import “NibCell.h”

@implementation NibCell

@synthesize callimgvw,imgvw;

– (void)awakeFromNib {

    // Initialization code

}

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

    }

    return self;

}

– (IBAction)pressButton:(id)sender {

    

    NSLog(@”%@”,sender);

    

        NSString *str = [NSString stringWithFormat:@”Button Clicked :: %ld”,(long)callimgvw.tag];

    

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@””

                                                        message:str

                                                       delegate:nil

                                              cancelButtonTitle:@”OK”

                                              otherButtonTitles:nil];

        [alert show];

    NSLog(@”%ld”,(long)callimgvw.tag);

}

@end

Download Sample Project From Github

Check Internet Reachability

ViewController.m

#import “Utility.h”

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    if ([Utility isNetworkReachable])

    {

        NSLog(@”Network Reachable”);

    }

    else

    {

        NSLog(@”Network is not Rechable”);

    }

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

@end

Utility.m

#import “Utility.h”

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    AppDelegate *aAppdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    Reachability *netReach = [aAppdelegate reachabile];

    

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    

    return isReachable;

}

@end

Download Sample  Project From Github

In App Purchase

ViewController.h

#import <UIKit/UIKit.h>

#import <StoreKit/StoreKit.h>

#import “SVProgressHUD.h”

@interface ViewController : UIViewController<SKProductsRequestDelegate,SKRequestDelegate,SKPaymentTransactionObserver>

{

    NSMutableArray *arr1;

    BOOL flag;

    NSString *pid;

}

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

  

    pid =@”com.preventheadche.unlock”;////

    

    arr1=[[NSMutableArray alloc]initWithObjects:@”one”,@”two”,@”three”,@”four”,@”five”,@”six”,@”seven”,@”eight”,@”nine”,@”ten”, nil];

    

    

    CGRect frame=[UIScreen mainScreen].bounds;

    float wd,ht;

    wd=frame.size.width;

    ht=frame.size.height;

    

    

    UITableView *tableView;

    

    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, wd, ht-100) style:UITableViewStylePlain];

    tableView.delegate = self;

    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor cyanColor];

    [self.view addSubview:tableView];

    

    UIButton *btn1;

    btn1=[UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn1.frame=CGRectMake(wd/2, ht-100, 100, 50);

    [btn1 setTitle:@”CLICK” forState:UIControlStateNormal];

    btn1.backgroundColor=[UIColor blueColor];

    [btn1 addTarget:self action:@selector(clickevent) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn1];

    

    flag=YES;

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    

    if(![[NSUserDefaults standardUserDefaults] boolForKey:@”AppPurchased”])

    {

        return 5;

    }

    else{

        return 10;

    }

    

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    

    UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”cell1″];

    cell.textLabel.text = [arr1 objectAtIndex:indexPath.row];

    

    return cell;

    

    

    

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    

}

-(void)clickevent

{

    

    NSLog(@”apple”);

    [self unlockAllRecipes];

    

}

– (void)unlockAllRecipes

{

    SKProductsRequest *request= [[SKProductsRequest alloc]

                                 initWithProductIdentifiers: [NSSet setWithObject:pid]];////

    request.delegate = self;

    [request start];

    

    [self showProgress:YES];

}

– (void)showProgress:(BOOL)inBool

{

    if(inBool)

    {

        [SVProgressHUD showInfoWithStatus:@”wait”];

    }

    else

    {

        [SVProgressHUD dismiss];

    }

}

#pragma mark – payment methods

– (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response

{

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

    

    NSArray *myProduct = response.products;

    NSLog(@”%@”,[[myProduct objectAtIndex:0] productIdentifier]);

    

    //Since only one product, we do not need to choose from the array. Proceed directly to payment.

    

    SKPayment *newPayment = [SKPayment paymentWithProduct:[myProduct objectAtIndex:0]];

    [[SKPaymentQueue defaultQueue] addPayment:newPayment];

}

– (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions

{

    for (SKPaymentTransaction *transaction in transactions)

    {

        switch (transaction.transactionState)

        {

            case SKPaymentTransactionStatePurchased:

                [self showProgress:NO];

                [self completeTransaction:transaction];

                break;

            case SKPaymentTransactionStateRestored:

                [self showProgress:NO];

                [self restoreTransaction:transaction];

                break;

            case SKPaymentTransactionStateFailed:

                [self showProgress:NO];

                [self failedTransaction:transaction];

                break;

            default:

                break;

        }

    }

}

– (void) completeTransaction: (SKPaymentTransaction *)transaction

{

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@”AppPurchased”];

    [[NSUserDefaults standardUserDefaults] synchronize];

    UIAlertView *alert;

    alert = [[UIAlertView alloc]initWithTitle:@”You have purchased successfully, thank you!” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

    [alert show];

    

}

– (void) restoreTransaction: (SKPaymentTransaction *)transaction

{

    NSLog(@”Transaction Restored”);

    // You can create a method to record the transaction.

    // [self recordTransaction: transaction];

    

    // You should make the update to your app based on what was purchased and inform user.

    // [self provideContent: transaction.payment.productIdentifier];

    

    // Finally, remove the transaction from the payment queue.

    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@”AppPurchased”];

    [[NSUserDefaults standardUserDefaults] synchronize];

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

    UIAlertView *alert;

    alert = [[UIAlertView alloc]initWithTitle:@”You have resotred successfully, thank you!” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

    [alert show];

    

}

– (void) failedTransaction: (SKPaymentTransaction *)transaction

{

    if (transaction.error.code != SKErrorPaymentCancelled)

    {

        // Display an error here.

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Purchase Unsuccessful”

                                                        message:@”Your purchase failed. Please try again.”

                                                       delegate:self

                                              cancelButtonTitle:@”OK”

                                              otherButtonTitles:nil];

        [alert show];

    }

    

    // Finally, remove the transaction from the payment queue.

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}

@end

SVProgressHUD.h

#import <UIKit/UIKit.h>

#import <AvailabilityMacros.h>

extern NSString * const SVProgressHUDDidReceiveTouchEventNotification;

extern NSString * const SVProgressHUDDidTouchDownInsideNotification;

extern NSString * const SVProgressHUDWillDisappearNotification;

extern NSString * const SVProgressHUDDidDisappearNotification;

extern NSString * const SVProgressHUDWillAppearNotification;

extern NSString * const SVProgressHUDDidAppearNotification;

extern NSString * const SVProgressHUDStatusUserInfoKey;

typedef NS_ENUM(NSUInteger, SVProgressHUDMaskType) {

    SVProgressHUDMaskTypeNone = 1,  // allow user interactions while HUD is displayed

    SVProgressHUDMaskTypeClear,     // don’t allow user interactions

    SVProgressHUDMaskTypeBlack,     // don’t allow user interactions and dim the UI in the back of the HUD

    SVProgressHUDMaskTypeGradient   // don’t allow user interactions and dim the UI with a a-la-alert-view background gradient

};

@interface SVProgressHUD : UIView

#pragma mark – Customization

+ (void)setBackgroundColor:(UIColor*)color;                 // default is [UIColor whiteColor]

+ (void)setForegroundColor:(UIColor*)color;                 // default is [UIColor blackColor]

+ (void)setRingThickness:(CGFloat)width;                    // default is 4 pt

+ (void)setFont:(UIFont*)font;                              // default is [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline]

+ (void)setInfoImage:(UIImage*)image;                       // default is the bundled info image provided by Freepik

+ (void)setSuccessImage:(UIImage*)image;                    // default is the bundled success image provided by Freepik

+ (void)setErrorImage:(UIImage*)image;                      // default is the bundled error image provided by Freepik

+ (void)setDefaultMaskType:(SVProgressHUDMaskType)maskType; // default is SVProgressHUDMaskTypeNone

+ (void)setViewForExtension:(UIView*)view;                  // default is nil, only used if #define SV_APP_EXTENSIONS is set

#pragma mark – Show Methods

+ (void)show;

+ (void)showWithMaskType:(SVProgressHUDMaskType)maskType;

+ (void)showWithStatus:(NSString*)status;

+ (void)showWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType;

+ (void)showProgress:(float)progress;

+ (void)showProgress:(float)progress maskType:(SVProgressHUDMaskType)maskType;

+ (void)showProgress:(float)progress status:(NSString*)status;

+ (void)showProgress:(float)progress status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType;

+ (void)setStatus:(NSString*)string; // change the HUD loading status while it’s showing

// stops the activity indicator, shows a glyph + status, and dismisses HUD a little bit later

+ (void)showInfoWithStatus:(NSString *)string;

+ (void)showInfoWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType;

+ (void)showSuccessWithStatus:(NSString*)string;

+ (void)showSuccessWithStatus:(NSString*)string maskType:(SVProgressHUDMaskType)maskType;

+ (void)showErrorWithStatus:(NSString *)string;

+ (void)showErrorWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType;

// use 28×28 white pngs

+ (void)showImage:(UIImage*)image status:(NSString*)status;

+ (void)showImage:(UIImage*)image status:(NSString*)status maskType:(SVProgressHUDMaskType)maskType;

+ (void)setOffsetFromCenter:(UIOffset)offset;

+ (void)resetOffsetFromCenter;

+ (void)popActivity; // decrease activity count, if activity count == 0 the HUD is dismissed

+ (void)dismiss;

+ (BOOL)isVisible;

@end

SVProgressHUD.m

#if !__has_feature(objc_arc)

#error SVProgressHUD is ARC only. Either turn on ARC for the project or use -fobjc-arc flag

#endif

#import “SVProgressHUD.h”

#import “SVIndefiniteAnimatedView.h”

#import <QuartzCore/QuartzCore.h>

NSString * const SVProgressHUDDidReceiveTouchEventNotification = @”SVProgressHUDDidReceiveTouchEventNotification”;

NSString * const SVProgressHUDDidTouchDownInsideNotification = @”SVProgressHUDDidTouchDownInsideNotification”;

NSString * const SVProgressHUDWillDisappearNotification = @”SVProgressHUDWillDisappearNotification”;

NSString * const SVProgressHUDDidDisappearNotification = @”SVProgressHUDDidDisappearNotification”;

NSString * const SVProgressHUDWillAppearNotification = @”SVProgressHUDWillAppearNotification”;

NSString * const SVProgressHUDDidAppearNotification = @”SVProgressHUDDidAppearNotification”;

NSString * const SVProgressHUDStatusUserInfoKey = @”SVProgressHUDStatusUserInfoKey”;

static UIColor *SVProgressHUDBackgroundColor;

static UIColor *SVProgressHUDForegroundColor;

static CGFloat SVProgressHUDRingThickness;

static UIFont *SVProgressHUDFont;

static UIImage *SVProgressHUDInfoImage;

static UIImage *SVProgressHUDSuccessImage;

static UIImage *SVProgressHUDErrorImage;

static SVProgressHUDMaskType SVProgressHUDDefaultMaskType;

static UIView *SVProgressHUDExtensionView;

static const CGFloat SVProgressHUDRingRadius = 18;

static const CGFloat SVProgressHUDRingNoTextRadius = 24;

static const CGFloat SVProgressHUDParallaxDepthPoints = 10;

static const CGFloat SVProgressHUDUndefinedProgress = –1;

@interface SVProgressHUD ()

@property (nonatomic, readwrite) SVProgressHUDMaskType maskType;

@property (nonatomic, strong, readonly) NSTimer *fadeOutTimer;

@property (nonatomic, readonly, getter = isClear) BOOL clear;

@property (nonatomic, strong) UIControl *overlayView;

@property (nonatomic, strong) UIView *hudView;

@property (nonatomic, strong) UILabel *stringLabel;

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) SVIndefiniteAnimatedView *indefiniteAnimatedView;

@property (nonatomic, readwrite) CGFloat progress;

@property (nonatomic, readwrite) NSUInteger activityCount;

@property (nonatomic, strong) CAShapeLayer *backgroundRingLayer;

@property (nonatomic, strong) CAShapeLayer *ringLayer;

@property (nonatomic, readonly) CGFloat visibleKeyboardHeight;

@property (nonatomic, assign) UIOffset offsetFromCenter;

– (void)showProgress:(float)progress status:(NSString*)string maskType:(SVProgressHUDMaskType)hudMaskType;

– (void)showImage:(UIImage*)image status:(NSString*)status duration:(NSTimeInterval)duration maskType:(SVProgressHUDMaskType)hudMaskType;

– (void)dismiss;

– (void)setStatus:(NSString*)string;

– (void)registerNotifications;

– (NSDictionary *)notificationUserInfo;

– (void)moveToPoint:(CGPoint)newCenter rotateAngle:(CGFloat)angle;

– (void)positionHUD:(NSNotification*)notification;

– (NSTimeInterval)displayDurationForString:(NSString*)string;

@end

@implementation SVProgressHUD

+ (SVProgressHUD*)sharedView {

    static dispatch_once_t once;

    static SVProgressHUD *sharedView;

    dispatch_once(&once, ^ { sharedView = [[self alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; });

    return sharedView;

}

#pragma mark – Setters

+ (void)setStatus:(NSString *)string {

[[self sharedView] setStatus:string];

}

+ (void)setBackgroundColor:(UIColor *)color {

    [self sharedView].hudView.backgroundColor = color;

    SVProgressHUDBackgroundColor = color;

}

+ (void)setForegroundColor:(UIColor *)color {

    [self sharedView];

    SVProgressHUDForegroundColor = color;

}

+ (void)setFont:(UIFont *)font {

    [self sharedView];

    SVProgressHUDFont = font;

}

+ (void)setRingThickness:(CGFloat)width {

    [self sharedView];

    SVProgressHUDRingThickness = width;

}

+ (void)setInfoImage:(UIImage*)image{

    [self sharedView];

    SVProgressHUDInfoImage = image;

}

+ (void)setSuccessImage:(UIImage *)image {

    [self sharedView];

    SVProgressHUDSuccessImage = image;

}

+ (void)setErrorImage:(UIImage *)image {

    [self sharedView];

    SVProgressHUDErrorImage = image;

}

+ (void)setDefaultMaskType:(SVProgressHUDMaskType)maskType{

    [self sharedView];

    SVProgressHUDDefaultMaskType = maskType;

}

+ (void)setViewForExtension:(UIView *)view{

    [self sharedView];

    SVProgressHUDExtensionView = view;

}

#pragma mark – Show Methods

+ (void)show {

    [self showWithStatus:nil];

}

+ (void)showWithMaskType:(SVProgressHUDMaskType)maskType {

    [self showProgress:SVProgressHUDUndefinedProgress maskType:maskType];

}

+ (void)showWithStatus:(NSString *)status {

    [self showProgress:SVProgressHUDUndefinedProgress status:status];

}

+ (void)showWithStatus:(NSString*)status maskType:(SVProgressHUDMaskType)maskType {

    [self showProgress:SVProgressHUDUndefinedProgress status:status maskType:maskType];

}

+ (void)showProgress:(float)progress {

    [self sharedView];

    [self showProgress:progress maskType:SVProgressHUDDefaultMaskType];

}

+ (void)showProgress:(float)progress maskType:(SVProgressHUDMaskType)maskType{

    [self showProgress:progress status:nil maskType:maskType];

}

+ (void)showProgress:(float)progress status:(NSString *)status {

    [self sharedView];

    [self showProgress:progress status:status maskType:SVProgressHUDDefaultMaskType];

}

+ (void)showProgress:(float)progress status:(NSString *)status maskType:(SVProgressHUDMaskType)maskType {

    [[self sharedView] showProgress:progress status:status maskType:maskType];

}

#pragma mark – Show then dismiss methods

+ (void)showInfoWithStatus:(NSString *)string {

    [self sharedView];

    [self showInfoWithStatus:string maskType:SVProgressHUDDefaultMaskType];

}

+ (void)showInfoWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType {

    [self sharedView];

    [self showImage:SVProgressHUDInfoImage status:string maskType:maskType];

}

+ (void)showSuccessWithStatus:(NSString *)string {

    [self sharedView];

    [self showSuccessWithStatus:string maskType:SVProgressHUDDefaultMaskType];

}

+ (void)showSuccessWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType {

    [self sharedView];

    [self showImage:SVProgressHUDSuccessImage status:string maskType:maskType];

}

+ (void)showErrorWithStatus:(NSString *)string {

    [self sharedView];

    [self showErrorWithStatus:string maskType:SVProgressHUDDefaultMaskType];

}

+ (void)showErrorWithStatus:(NSString *)string maskType:(SVProgressHUDMaskType)maskType {

    [self sharedView];

    [self showImage:SVProgressHUDErrorImage status:string maskType:maskType];

}

+ (void)showImage:(UIImage *)image status:(NSString *)string {

    [self sharedView];

    [self showImage:image status:string maskType:SVProgressHUDDefaultMaskType];

}

+ (void)showImage:(UIImage *)image status:(NSString *)string maskType:(SVProgressHUDMaskType)maskType {

    NSTimeInterval displayInterval = [[self sharedView] displayDurationForString:string];

    [[self sharedView] showImage:image status:string duration:displayInterval maskType:maskType];

}

#pragma mark – Dismiss Methods

+ (void)popActivity {

    if([self sharedView].activityCount > 0)

        [self sharedView].activityCount–;

    if([self sharedView].activityCount == 0)

        [[self sharedView] dismiss];

}

+ (void)dismiss {

    if ([self isVisible]) {

        [[self sharedView] dismiss];

    }

}

#pragma mark – Offset

+ (void)setOffsetFromCenter:(UIOffset)offset {

    [self sharedView].offsetFromCenter = offset;

}

+ (void)resetOffsetFromCenter {

    [self setOffsetFromCenter:UIOffsetZero];

}

#pragma mark – Instance Methods

– (id)initWithFrame:(CGRect)frame {

    if ((self = [super initWithFrame:frame])) {

self.userInteractionEnabled = NO;

        self.backgroundColor = [UIColor clearColor];

self.alpha = 0.0f;

        self.activityCount = 0;

        

        SVProgressHUDBackgroundColor = [UIColor whiteColor];

        SVProgressHUDForegroundColor = [UIColor blackColor];

        if ([UIFont respondsToSelector:@selector(preferredFontForTextStyle:)]) {

            SVProgressHUDFont = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];

        } else {

            SVProgressHUDFont = [UIFont systemFontOfSize:14.0f];

            SVProgressHUDBackgroundColor = [UIColor colorWithWhite:0.0f alpha:0.8f];

            SVProgressHUDForegroundColor = [UIColor whiteColor];

        }

        

        UIImage* infoImage = [UIImage imageNamed:@”SVProgressHUD.bundle/info”];

        UIImage* successImage = [UIImage imageNamed:@”SVProgressHUD.bundle/success”];

        UIImage* errorImage = [UIImage imageNamed:@”SVProgressHUD.bundle/error”];

        if ([[UIImage class] instancesRespondToSelector:@selector(imageWithRenderingMode:)]) {

            SVProgressHUDInfoImage = [infoImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

            SVProgressHUDSuccessImage = [successImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

            SVProgressHUDErrorImage = [errorImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

        } else {

            SVProgressHUDInfoImage = infoImage;

            SVProgressHUDSuccessImage = successImage;

            SVProgressHUDErrorImage = errorImage;

        }

        SVProgressHUDRingThickness = 2;

        SVProgressHUDDefaultMaskType = SVProgressHUDMaskTypeNone;

    }

    return self;

}

– (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    switch (self.maskType) {

        case SVProgressHUDMaskTypeBlack: {

            

            [[UIColor colorWithWhite:0 alpha:0.5] set];

            CGContextFillRect(context, self.bounds);

            

            break;

        }

        case SVProgressHUDMaskTypeGradient: {

            

            size_t locationsCount = 2;

            CGFloat locations[2] = {0.0f, 1.0f};

            CGFloat colors[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f};

            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

            CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colors, locations, locationsCount);

            CGColorSpaceRelease(colorSpace);

            

            CGFloat freeHeight = CGRectGetHeight(self.bounds) – self.visibleKeyboardHeight;

            

            CGPoint center = CGPointMake(CGRectGetWidth(self.bounds)/2, freeHeight/2);

            float radius = MIN(CGRectGetWidth(self.bounds) , CGRectGetHeight(self.bounds)) ;

            CGContextDrawRadialGradient (context, gradient, center, 0, center, radius, kCGGradientDrawsAfterEndLocation);

            CGGradientRelease(gradient);

            

            break;

        }

        default:

            break;

    }

}

– (void)updatePosition {

    CGFloat hudWidth = 100.0f;

    CGFloat hudHeight = 100.0f;

    CGFloat stringHeightBuffer = 20.0f;

    CGFloat stringAndContentHeightBuffer = 80.0f;

    

    CGFloat stringWidth = 0.0f;

    CGFloat stringHeight = 0.0f;

    CGRect labelRect = CGRectZero;

    

    NSString *string = self.stringLabel.text;

    

    // Check if an image or progress ring is displayed

    BOOL imageUsed = (self.imageView.image) || (self.imageView.hidden);

    BOOL progressUsed = (self.progress != SVProgressHUDUndefinedProgress) && (self.progress >= 0.0f);

    

    if(string) {

        CGSize constraintSize = CGSizeMake(200.0f, 300.0f);

        CGRect stringRect;

        if ([string respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {

          stringRect = [string boundingRectWithSize:constraintSize

                                            options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin)

                                         attributes:@{NSFontAttributeName: self.stringLabel.font}

                                            context:NULL];

        } else {

            CGSize stringSize;

            

            if ([string respondsToSelector:@selector(sizeWithAttributes:)])

                stringSize = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:self.stringLabel.font.fontName size:self.stringLabel.font.pointSize]}];

            else

#pragma clang diagnostic push

#pragma clang diagnostic ignored “-Wdeprecated”

                stringSize = [string sizeWithFont:self.stringLabel.font constrainedToSize:CGSizeMake(200.0f, 300.0f)];

#pragma clang diagnostic pop

            

            stringRect = CGRectMake(0.0f, 0.0f, stringSize.width, stringSize.height);

        }

        stringWidth = stringRect.size.width;

        stringHeight = ceil(CGRectGetHeight(stringRect));

        

        if (imageUsed || progressUsed)

            hudHeight = stringAndContentHeightBuffer + stringHeight;

        else

            hudHeight = stringHeightBuffer + stringHeight;

        

        if(stringWidth > hudWidth)

            hudWidth = ceil(stringWidth/2)*2;

        

        CGFloat labelRectY = (imageUsed || progressUsed) ? 68.0f : 9.0f;

        

        if(hudHeight > 100.0f) {

            labelRect = CGRectMake(12.0f, labelRectY, hudWidth, stringHeight);

            hudWidth += 24.0f;

        } else {

            hudWidth += 24.0f;

            labelRect = CGRectMake(0.0f, labelRectY, hudWidth, stringHeight);

        }

    }

self.hudView.bounds = CGRectMake(0.0f, 0.0f, hudWidth, hudHeight);

    

    if(string)

        self.imageView.center = CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, 36.0f);

else

       self.imageView.center = CGPointMake(CGRectGetWidth(self.hudView.bounds)/2, CGRectGetHeight(self.hudView.bounds)/2);

self.stringLabel.hidden = NO;

self.stringLabel.frame = labelRect;

    

    [CATransaction begin];

    [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];

if(string) {

        self.indefiniteAnimatedView.radius = SVProgressHUDRingRadius;

        [self.indefiniteAnimatedView sizeToFit];

        

        CGPoint center = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), 36.0f);

        self.indefiniteAnimatedView.center = center;

        

        if(self.progress != SVProgressHUDUndefinedProgress)

            self.backgroundRingLayer.position = self.ringLayer.position = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), 36.0f);

} else {

        self.indefiniteAnimatedView.radius = SVProgressHUDRingNoTextRadius;

        [self.indefiniteAnimatedView sizeToFit];

        

        CGPoint center = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), CGRectGetHeight(self.hudView.bounds)/2);

        self.indefiniteAnimatedView.center = center;

        

        if(self.progress != SVProgressHUDUndefinedProgress)

            self.backgroundRingLayer.position = self.ringLayer.position = CGPointMake((CGRectGetWidth(self.hudView.bounds)/2), CGRectGetHeight(self.hudView.bounds)/2);

    }

    

    [CATransaction commit];

}

– (void)setStatus:(NSString *)string {

self.stringLabel.text = string;

    [self updatePosition];

    

}

– (void)setFadeOutTimer:(NSTimer *)newTimer {

    if(_fadeOutTimer)

        [_fadeOutTimer invalidate], _fadeOutTimer = nil;

    

    if(newTimer)

        _fadeOutTimer = newTimer;

}

– (void)registerNotifications {

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(positionHUD:)

                                                 name:UIApplicationDidChangeStatusBarOrientationNotification

                                               object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(positionHUD:)

                                                 name:UIKeyboardWillHideNotification

                                               object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(positionHUD:)

                                                 name:UIKeyboardDidHideNotification

                                               object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(positionHUD:)

                                                 name:UIKeyboardWillShowNotification

                                               object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(positionHUD:)

                                                 name:UIKeyboardDidShowNotification

                                               object:nil];

}

– (NSDictionary *)notificationUserInfo{

    return (self.stringLabel.text ? @{SVProgressHUDStatusUserInfoKey : self.stringLabel.text} : nil);

}

– (void)positionHUD:(NSNotification*)notification {

    

    CGFloat keyboardHeight = 0.0f;

    double animationDuration = 0.0;

    

    self.frame = UIScreen.mainScreen.bounds;

    

#if !defined(SV_APP_EXTENSIONS)

    UIInterfaceOrientation orientation = UIApplication.sharedApplication.statusBarOrientation;

#else

    UIInterfaceOrientation orientation = CGRectGetWidth(self.frame) > CGRectGetHeight(self.frame) ? UIInterfaceOrientationLandscapeLeft : UIInterfaceOrientationPortrait;

#endif

    // no transforms applied to window in iOS 8, but only if compiled with iOS 8 sdk as base sdk, otherwise system supports old rotation logic.

    BOOL ignoreOrientation = NO;

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000

    if ([[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {

        ignoreOrientation = YES;

    }

#endif

    if(notification) {

        NSDictionary* keyboardInfo = [notification userInfo];

        CGRect keyboardFrame = [[keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

        animationDuration = [[keyboardInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

        

        if(notification.name == UIKeyboardWillShowNotification || notification.name == UIKeyboardDidShowNotification) {

            if(ignoreOrientation || UIInterfaceOrientationIsPortrait(orientation))

                keyboardHeight = CGRectGetHeight(keyboardFrame);

            else

                keyboardHeight = CGRectGetWidth(keyboardFrame);

        }

    } else {

        keyboardHeight = self.visibleKeyboardHeight;

    }

    

    CGRect orientationFrame = self.bounds;

#if !defined(SV_APP_EXTENSIONS)

    CGRect statusBarFrame = UIApplication.sharedApplication.statusBarFrame;

#else

    CGRect statusBarFrame = CGRectZero;

#endif

    

    if(!ignoreOrientation && UIInterfaceOrientationIsLandscape(orientation)) {

        float temp = CGRectGetWidth(orientationFrame);

        orientationFrame.size.width = CGRectGetHeight(orientationFrame);

        orientationFrame.size.height = temp;

        

        temp = CGRectGetWidth(statusBarFrame);

        statusBarFrame.size.width = CGRectGetHeight(statusBarFrame);

        statusBarFrame.size.height = temp;

    }

    

    CGFloat activeHeight = CGRectGetHeight(orientationFrame);

    

    if(keyboardHeight > 0)

        activeHeight += CGRectGetHeight(statusBarFrame)*2;

    

    activeHeight -= keyboardHeight;

    CGFloat posY = floor(activeHeight*0.45);

    CGFloat posX = CGRectGetWidth(orientationFrame)/2;

    

    CGPoint newCenter;

    CGFloat rotateAngle;

    

    if (ignoreOrientation) {

        rotateAngle = 0.0;

        newCenter = CGPointMake(posX, posY);

    } else {

        switch (orientation) {

            case UIInterfaceOrientationPortraitUpsideDown:

                rotateAngle = M_PI;

                newCenter = CGPointMake(posX, CGRectGetHeight(orientationFrame)-posY);

                break;

            case UIInterfaceOrientationLandscapeLeft:

                rotateAngle = -M_PI/2.0f;

                newCenter = CGPointMake(posY, posX);

                break;

            case UIInterfaceOrientationLandscapeRight:

                rotateAngle = M_PI/2.0f;

                newCenter = CGPointMake(CGRectGetHeight(orientationFrame)-posY, posX);

                break;

            default: // as UIInterfaceOrientationPortrait

                rotateAngle = 0.0;

                newCenter = CGPointMake(posX, posY);

                break;

        }

    }

    

    if(notification) {

        [UIView animateWithDuration:animationDuration

                              delay:0

                            options:UIViewAnimationOptionAllowUserInteraction

                         animations:^{

                             [self moveToPoint:newCenter rotateAngle:rotateAngle];

                             [self.hudView setNeedsDisplay];

                         } completion:NULL];

    } else {

        [self moveToPoint:newCenter rotateAngle:rotateAngle];

        [self.hudView setNeedsDisplay];

    }

    

}

– (void)moveToPoint:(CGPoint)newCenter rotateAngle:(CGFloat)angle {

    self.hudView.transform = CGAffineTransformMakeRotation(angle);

    self.hudView.center = CGPointMake(newCenter.x + self.offsetFromCenter.horizontal, newCenter.y + self.offsetFromCenter.vertical);

}

– (void)overlayViewDidReceiveTouchEvent:(id)sender forEvent:(UIEvent *)event {

    [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidReceiveTouchEventNotification object:event];

    

    UITouch *touch = event.allTouches.anyObject;

    CGPoint touchLocation = [touch locationInView:self];

    

    if (CGRectContainsPoint(self.hudView.frame, touchLocation)) {

        [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidTouchDownInsideNotification object:event];

    }

}

#pragma mark – Master show/dismiss methods

– (void)showProgress:(float)progress status:(NSString*)string maskType:(SVProgressHUDMaskType)hudMaskType {

    if(!self.overlayView.superview){

#if !defined(SV_APP_EXTENSIONS)

        NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];

        for (UIWindow *window in frontToBackWindows){

            BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;

            BOOL windowIsVisible = !window.hidden && window.alpha > 0;

            BOOL windowLevelNormal = window.windowLevel == UIWindowLevelNormal;

            

            if (windowOnMainScreen && windowIsVisible && windowLevelNormal) {

                [window addSubview:self.overlayView];

                break;

            }

        }

#else

        if(SVProgressHUDExtensionView){

            [SVProgressHUDExtensionView addSubview:self.overlayView];

        }

#endif

    } else {

        // Ensure that overlay will be exactly on top of rootViewController (which may be changed during runtime).

        [self.overlayView.superview bringSubviewToFront:self.overlayView];

    }

    

    if(!self.superview)

        [self.overlayView addSubview:self];

    

    self.fadeOutTimer = nil;

    self.imageView.hidden = YES;

    self.maskType = hudMaskType;

    self.progress = progress;

    

    self.stringLabel.text = string;

    [self updatePosition];

    

    if(progress >= 0) {

        self.imageView.image = nil;

        self.imageView.hidden = NO;

        [self.indefiniteAnimatedView removeFromSuperview];

        

        self.ringLayer.strokeEnd = progress;

        

        if(progress == 0)

            self.activityCount++;

    } else {

        self.activityCount++;

        [self cancelRingLayerAnimation];

        [self.hudView addSubview:self.indefiniteAnimatedView];

    }

    

    if(self.maskType != SVProgressHUDMaskTypeNone) {

        self.overlayView.userInteractionEnabled = YES;

        self.accessibilityLabel = string;

        self.isAccessibilityElement = YES;

    } else {

        self.overlayView.userInteractionEnabled = NO;

        self.hudView.accessibilityLabel = string;

        self.hudView.isAccessibilityElement = YES;

    }

    

    [self.overlayView setHidden:NO];

    self.overlayView.backgroundColor = [UIColor clearColor];

    [self positionHUD:nil];

    

    if(self.alpha != 1 || self.hudView.alpha != 1) {

        NSDictionary *userInfo = [self notificationUserInfo];

        [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillAppearNotification

                                                            object:nil

                                                          userInfo:userInfo];

        

        [self registerNotifications];

        self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 1.3, 1.3);

        

        if(self.isClear) {

            self.alpha = 1;

            self.hudView.alpha = 0;

        }

        

        [UIView animateWithDuration:0.15

                              delay:0

                            options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState

                         animations:^{

                             self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 1/1.3, 1/1.3);

                             

                             if(self.isClear) // handle iOS 7 and 8 UIToolbar which not answers well to hierarchy opacity change

                                 self.hudView.alpha = 1;

                             else

                                 self.alpha = 1;

                         }

                         completion:^(BOOL finished){

                             [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidAppearNotification

                                                                                 object:nil

                                                                               userInfo:userInfo];

                             UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

                             UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, string);

                         }];

        

        [self setNeedsDisplay];

    }

}

– (UIImage *)image:(UIImage *)image withTintColor:(UIColor *)color{

    CGRect rect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);

    UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);

    CGContextRef c = UIGraphicsGetCurrentContext();

    [image drawInRect:rect];

    CGContextSetFillColorWithColor(c, [color CGColor]);

    CGContextSetBlendMode(c, kCGBlendModeSourceAtop);

    CGContextFillRect(c, rect);

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return tintedImage;

}

– (void)showImage:(UIImage *)image status:(NSString *)string duration:(NSTimeInterval)duration maskType:(SVProgressHUDMaskType)hudMaskType {

    self.progress = SVProgressHUDUndefinedProgress;

    self.maskType = hudMaskType;

    [self cancelRingLayerAnimation];

    

    if(![self.class isVisible])

        [self.class showWithMaskType:self.maskType];

  

    if ([self.imageView respondsToSelector:@selector(setTintColor:)]) {

        self.imageView.tintColor = SVProgressHUDForegroundColor;

    } else {

        image = [self image:image withTintColor:SVProgressHUDForegroundColor];

    }

    self.imageView.image = image;

    self.imageView.hidden = NO;

    

    self.stringLabel.text = string;

    [self updatePosition];

    [self.indefiniteAnimatedView removeFromSuperview];

    

    if(self.maskType != SVProgressHUDMaskTypeNone) {

        self.overlayView.userInteractionEnabled = YES;

        self.accessibilityLabel = string;

        self.isAccessibilityElement = YES;

    } else {

        self.overlayView.userInteractionEnabled = NO;

        self.hudView.accessibilityLabel = string;

        self.hudView.isAccessibilityElement = YES;

    }

    

    UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

    UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, string);

    

    self.fadeOutTimer = [NSTimer timerWithTimeInterval:duration target:self selector:@selector(dismiss) userInfo:nil repeats:NO];

    [[NSRunLoop mainRunLoop] addTimer:self.fadeOutTimer forMode:NSRunLoopCommonModes];

}

– (void)dismiss {

    NSDictionary *userInfo = [self notificationUserInfo];

    [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDWillDisappearNotification

                                                        object:nil

                                                      userInfo:userInfo];

    

    self.activityCount = 0;

    [UIView animateWithDuration:0.15

                          delay:0

                        options:UIViewAnimationCurveEaseIn | UIViewAnimationOptionAllowUserInteraction

                     animations:^{

                         self.hudView.transform = CGAffineTransformScale(self.hudView.transform, 0.8f, 0.8f);

                         if(self.isClear) // handle iOS 7 UIToolbar not answer well to hierarchy opacity change

                             self.hudView.alpha = 0.0f;

                         else

                             self.alpha = 0.0f;

                     }

                     completion:^(BOOL finished){

                         if(self.alpha == 0.0f || self.hudView.alpha == 0.0f) {

                             self.alpha = 0.0f;

                             self.hudView.alpha = 0.0f;

                             

                             [[NSNotificationCenter defaultCenter] removeObserver:self];

                             [self cancelRingLayerAnimation];

                             [_hudView removeFromSuperview];

                             _hudView = nil;

                             

                             [_overlayView removeFromSuperview];

                             _overlayView = nil;

                             

                             [_indefiniteAnimatedView removeFromSuperview];

                             _indefiniteAnimatedView = nil;

                             

                             UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);

                             

                             [[NSNotificationCenter defaultCenter] postNotificationName:SVProgressHUDDidDisappearNotification

                                                                                 object:nil

                                                                               userInfo:userInfo];

                             

                             // Tell the rootViewController to update the StatusBar appearance

#if !defined(SV_APP_EXTENSIONS)

                             UIViewController *rootController = [[UIApplication sharedApplication] keyWindow].rootViewController;

                             if ([rootController respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {

                                 [rootController setNeedsStatusBarAppearanceUpdate];

                             }

#endif

                             // uncomment to make sure UIWindow is gone from app.windows

                             //NSLog(@”%@”, [UIApplication sharedApplication].windows);

                             //NSLog(@”keyWindow = %@”, [UIApplication sharedApplication].keyWindow);

                         }

                     }];

}

#pragma mark – Ring progress animation

– (SVIndefiniteAnimatedView *)indefiniteAnimatedView {

    if (_indefiniteAnimatedView == nil) {

        _indefiniteAnimatedView = [[SVIndefiniteAnimatedView alloc] initWithFrame:CGRectZero];

        _indefiniteAnimatedView.strokeThickness = SVProgressHUDRingThickness;

        _indefiniteAnimatedView.strokeColor = SVProgressHUDForegroundColor;

        _indefiniteAnimatedView.radius = self.stringLabel.text ? SVProgressHUDRingRadius : SVProgressHUDRingNoTextRadius;

        [_indefiniteAnimatedView sizeToFit];

    }

    return _indefiniteAnimatedView;

}

– (CAShapeLayer *)ringLayer {

    if(!_ringLayer) {

        CGPoint center = CGPointMake(CGRectGetWidth(_hudView.frame)/2, CGRectGetHeight(_hudView.frame)/2);

        _ringLayer = [self createRingLayerWithCenter:center

                                              radius:SVProgressHUDRingRadius

                                           lineWidth:SVProgressHUDRingThickness

                                               color:SVProgressHUDForegroundColor];

        [self.hudView.layer addSublayer:_ringLayer];

    }

    return _ringLayer;

}

– (CAShapeLayer *)backgroundRingLayer {

    if(!_backgroundRingLayer) {

        CGPoint center = CGPointMake(CGRectGetWidth(_hudView.frame)/2, CGRectGetHeight(_hudView.frame)/2);

        _backgroundRingLayer = [self createRingLayerWithCenter:center

                                                        radius:SVProgressHUDRingRadius

                                                     lineWidth:SVProgressHUDRingThickness

                                                         color:[SVProgressHUDForegroundColor colorWithAlphaComponent:0.1f]];

        _backgroundRingLayer.strokeEnd = 1;

        [self.hudView.layer addSublayer:_backgroundRingLayer];

    }

    return _backgroundRingLayer;

}

– (void)cancelRingLayerAnimation {

    [CATransaction begin];

    [CATransaction setDisableActions:YES];

    [_hudView.layer removeAllAnimations];

    

    _ringLayer.strokeEnd = 0.0f;

    if (_ringLayer.superlayer) {

        [_ringLayer removeFromSuperlayer];

    }

    _ringLayer = nil;

    

    if (_backgroundRingLayer.superlayer) {

        [_backgroundRingLayer removeFromSuperlayer];

    }

    _backgroundRingLayer = nil;

    

    [CATransaction commit];

}

– (CAShapeLayer *)createRingLayerWithCenter:(CGPoint)center radius:(CGFloat)radius lineWidth:(CGFloat)lineWidth color:(UIColor *)color {

    

    UIBezierPath* smoothedPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius startAngle:-M_PI_2 endAngle:(M_PI + M_PI_2) clockwise:YES];

    

    CAShapeLayer *slice = [CAShapeLayer layer];

    slice.contentsScale = [[UIScreen mainScreen] scale];

    slice.frame = CGRectMake(center.x-radius, center.y-radius, radius*2, radius*2);

    slice.fillColor = [UIColor clearColor].CGColor;

    slice.strokeColor = color.CGColor;

    slice.lineWidth = lineWidth;

    slice.lineCap = kCALineCapRound;

    slice.lineJoin = kCALineJoinBevel;

    slice.path = smoothedPath.CGPath;

    

    return slice;

}

#pragma mark – Utilities

+ (BOOL)isVisible {

    return ([self sharedView].alpha == 1);

}

#pragma mark – Getters

– (NSTimeInterval)displayDurationForString:(NSString*)string {

    return MIN((float)string.length*0.06 + 0.5, 5.0);

}

– (BOOL)isClear { // used for iOS 7 and above

    return (self.maskType == SVProgressHUDMaskTypeClear || self.maskType == SVProgressHUDMaskTypeNone);

}

– (UIControl *)overlayView {

    if(!_overlayView) {

        _overlayView = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];

        _overlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        _overlayView.backgroundColor = [UIColor clearColor];

        [_overlayView addTarget:self action:@selector(overlayViewDidReceiveTouchEvent:forEvent:) forControlEvents:UIControlEventTouchDown];

    }

    return _overlayView;

}

– (UIView *)hudView {

    if(!_hudView) {

        _hudView = [[UIView alloc] initWithFrame:CGRectZero];

        _hudView.backgroundColor = SVProgressHUDBackgroundColor;

        _hudView.layer.cornerRadius = 14;

        _hudView.layer.masksToBounds = YES;

        _hudView.autoresizingMask = (UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin |

                                     UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin);

        if ([_hudView respondsToSelector:@selector(addMotionEffect:)]) {

            UIInterpolatingMotionEffect *effectX = [[UIInterpolatingMotionEffect alloc] initWithKeyPath: @”center.x” type: UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];

            effectX.minimumRelativeValue = @(-SVProgressHUDParallaxDepthPoints);

            effectX.maximumRelativeValue = @(SVProgressHUDParallaxDepthPoints);

            UIInterpolatingMotionEffect *effectY = [[UIInterpolatingMotionEffect alloc] initWithKeyPath: @”center.y” type: UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];

            effectY.minimumRelativeValue = @(-SVProgressHUDParallaxDepthPoints);

            effectY.maximumRelativeValue = @(SVProgressHUDParallaxDepthPoints);

            UIMotionEffectGroup *effectGroup = [[UIMotionEffectGroup alloc] init];

            effectGroup.motionEffects = @[effectX, effectY];

            [_hudView addMotionEffect:effectGroup];

        }

    }

    

    if(!_hudView.superview)

        [self addSubview:_hudView];

    

    return _hudView;

}

– (UILabel *)stringLabel {

    if (!_stringLabel) {

        _stringLabel = [[UILabel alloc] initWithFrame:CGRectZero];

_stringLabel.backgroundColor = [UIColor clearColor];

_stringLabel.adjustsFontSizeToFitWidth = YES;

        _stringLabel.textAlignment = NSTextAlignmentCenter;

_stringLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

        _stringLabel.numberOfLines = 0;

    }

    

    if(!_stringLabel.superview)

        [self.hudView addSubview:_stringLabel];

    _stringLabel.textColor = SVProgressHUDForegroundColor;

    _stringLabel.font = SVProgressHUDFont;

    

    return _stringLabel;

}

– (UIImageView *)imageView {

    if (!_imageView)

        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 28.0f, 28.0f)];

    

    if(!_imageView.superview)

        [self.hudView addSubview:_imageView];

    

    return _imageView;

}

– (CGFloat)visibleKeyboardHeight {

#if !defined(SV_APP_EXTENSIONS)

    UIWindow *keyboardWindow = nil;

    for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {

        if(![[testWindow class] isEqual:[UIWindow class]]) {

            keyboardWindow = testWindow;

            break;

        }

    }

    

    for (__strong UIView *possibleKeyboard in [keyboardWindow subviews]) {

        if ([possibleKeyboard isKindOfClass:NSClassFromString(@”UIPeripheralHostView”)] || [possibleKeyboard isKindOfClass:NSClassFromString(@”UIKeyboard”)]) {

            return CGRectGetHeight(possibleKeyboard.bounds);

        } else if ([possibleKeyboard isKindOfClass:NSClassFromString(@”UIInputSetContainerView”)]) {

            for (__strong UIView *possibleKeyboardSubview in [possibleKeyboard subviews]) {

                if ([possibleKeyboardSubview isKindOfClass:NSClassFromString(@”UIInputSetHostView”)]) {

                    return CGRectGetHeight(possibleKeyboardSubview.bounds);

                }

            }

        }

    }

#endif

    return 0;

}

@end

Download Sample Project From Github

Image Downloading Show in ProgressView

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLSessionDelegate, NSURLSessionDownloadDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@”https://i.ytimg.com/vi/QGiJFumHUPo/maxresdefault.jpg&#8221;]];

    [downloadTask resume];

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {

    NSData *data = [NSData dataWithContentsOfURL:location];

    

    dispatch_async(dispatch_get_main_queue(), ^{

        //[self.progressView setHidden:YES];

        [self.imageView setImage:[UIImage imageWithData:data]];

    });

}

– (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

    

}

– (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

    float progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;

    

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.progressView setProgress:progress];

    });

}

@end

Download Sample Project From Github

Image Animation Twelve With Round Moving

ViewController.h

#import <UIKit/UIKit.h>

#import “EFAnimationViewController.h”

@interface ViewController : UIViewController

@property (nonatomic, strong) EFAnimationViewController *aEFAnimationVC;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.aEFAnimationVC = ({

        EFAnimationViewController *aEFAnimationVC = [[EFAnimationViewController alloc] init];

        [self.view addSubview:aEFAnimationVC.view];

        [self addChildViewController:aEFAnimationVC];

        [aEFAnimationVC didMoveToParentViewController:self];

        aEFAnimationVC;

    });

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (void)dealloc

{

    [_aEFAnimationVC.view removeFromSuperview];

    [_aEFAnimationVC removeFromParentViewController];

}

@end

EFAnimationViewController.h

#import <UIKit/UIKit.h>

@interface EFAnimationViewController : UIViewController

@end

@protocol EFItemViewDelegate <NSObject>

– (void)didTapped:(NSInteger)index;

@end

@interface EFItemView : UIButton

@property (nonatomic, weak) id <EFItemViewDelegate>delegate;

– (instancetype)initWithNormalImage:(NSString *)normal highlightedImage:(NSString *)highlighted tag:(NSInteger)tag title:(NSString *)title;

@end

EFAnimationViewController.m

#import “EFAnimationViewController.h”

#define RADIUS 150.0

#define PHOTONUM 12

#define TAGSTART 1

#define TIME 5

#define SCALENUMBER 0.7

NSInteger array [PHOTONUM][PHOTONUM] = {

    {0,1,2,3,4,5,6,7,8,9,10,11},

    {11,0,1,2,3,4,5,6,7,8,9,10},

    {10,11,0,1,2,3,4,5,6,7,8,9},

    {9,10,11,0,1,2,3,4,5,6,7,8},

    {8,9,10,11,0,1,2,3,4,5,6,7},

    {7,8,9,10,11,0,1,2,3,4,5,6},

    {6,7,8,9,10,11,0,1,2,3,4,5},

    {5,6,7,8,9,10,11,0,1,2,3,4},

    {4,5,6,7,8,9,10,11,0,1,2,3},

    {3,4,5,6,7,8,9,10,11,0,1,2},

    {2,3,4,5,6,7,8,9,10,11,0,1},

    {1,2,3,4,5,6,7,8,9,10,11,0},

};

@interface EFAnimationViewController ()<EFItemViewDelegate>

@property (nonatomic, assign) NSInteger currentTag;

@end

@implementation EFAnimationViewController

CATransform3D rotationTransform1[PHOTONUM];

– (void)viewDidLoad {

    

    [super viewDidLoad];

    

    [self configViews];

    [self didTapped:1];

    

    

}

#pragma mark – configViews

– (void)configViews {

    

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@”common_background”]];

    NSArray *dataArray = @[@”AddressChange”, @”Finances and Banking”, @”HomeSecurity”, @”HomeServices”, @”Insurance”,@”Internet”,@”Mortgage”, @”Movermusle”, @”Packing”, @”Pets”, @”Storage”,@”Utilities”];

    

    CGFloat centerx = self.view.center.x;

    CGFloat centery = self.view.center.y + 100;

    

    

    for (NSInteger i = 0;i < PHOTONUM;i++)

    {

        CGFloat tmpy =  centery + RADIUS*cos(2.0*M_PI *i/PHOTONUM);

        CGFloat tmpx = centerx – RADIUS*sin(2.0*M_PI *i/PHOTONUM);

        EFItemView *view = [[EFItemView alloc] initWithNormalImage:dataArray[i] highlightedImage:dataArray[i] tag:TAGSTART+i title:nil];

        view.frame = CGRectMake(0.0, 0.0,115,115);

        view.center = CGPointMake(tmpx,tmpy);

        view.delegate = self;

        rotationTransform1[i] = CATransform3DIdentity;

        

        CGFloat Scalenumber = fabs(i – PHOTONUM/2.0)/(PHOTONUM/2.0);

        if (Scalenumber < 0.3)

        {

            Scalenumber = 0.4;

        }

        CATransform3D rotationTransform = CATransform3DIdentity;

        rotationTransform = CATransform3DScale (rotationTransform, Scalenumber*SCALENUMBER,Scalenumber*SCALENUMBER, 1);

        view.layer.transform=rotationTransform;

        [self.view addSubview:view];

        

    }

    self.currentTag = TAGSTART;

}

#pragma mark – EFItemViewDelegate

– (void)didTapped:(NSInteger)index

{

    

//    if (self.currentTag  == index)

//    {

//        NSLog(@”%ld”,index);

//        return;

//    }

    

    NSInteger t = [self getIemViewTag:index];

    

    for (NSInteger i = 0;i<PHOTONUM;i++ )

    {

        

        UIView *view = [self.view viewWithTag:TAGSTART+i];

        [view.layer addAnimation:[self moveanimation:TAGSTART+i number:t] forKey:@”position”];

//        [view.layer addAnimation:[self setscale:TAGSTART+i clicktag:index] forKey:@”transform”];

        

        NSInteger j = array[index – TAGSTART][i];

        CGFloat Scalenumber = fabs(j – PHOTONUM/2.0)/(PHOTONUM/2.0);

        if (Scalenumber < 0.3)

        {

            Scalenumber = 0.4;

        }

    }

    self.currentTag  = index;

    

    

}

//- (CAAnimation*)setscale:(NSInteger)tag clicktag:(NSInteger)clicktag

//{

//    

//    NSInteger i = array[clicktag – TAGSTART][tag – TAGSTART];

//    NSInteger i1 = array[self.currentTag  – TAGSTART][tag – TAGSTART];

//    CGFloat Scalenumber = fabs(i – PHOTONUM/2.0)/(PHOTONUM/2.0);

//    CGFloat Scalenumber1 = fabs(i1 – PHOTONUM/2.0)/(PHOTONUM/2.0);

//    if (Scalenumber < 0.3)

//    {

//        Scalenumber = 0.4;

//    }

//    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@”transform”];

//    animation.duration = TIME;

//    animation.repeatCount =1;

//    

//    CATransform3D dtmp = CATransform3DScale(rotationTransform1[tag – TAGSTART],Scalenumber*SCALENUMBER, Scalenumber*SCALENUMBER, 1.0);

//    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DScale(rotationTransform1[tag – TAGSTART],Scalenumber1*SCALENUMBER,Scalenumber1*SCALENUMBER, 1.0)];

//    animation.toValue = [NSValue valueWithCATransform3D:dtmp ];

//    animation.autoreverses = NO;

//    animation.removedOnCompletion = NO;

//    animation.fillMode = kCAFillModeForwards;

//    

//    return animation;

//}

– (CAAnimation*)moveanimation:(NSInteger)tag number:(NSInteger)num

{

    // CALayer

    UIView *view = [self.view viewWithTag:tag];

    CAKeyframeAnimation* animation;

    animation = [CAKeyframeAnimation animation];

    

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL,view.layer.position.x,view.layer.position.y);

    

    NSInteger p =  [self getIemViewTag:tag];

    CGFloat f = 2.0*M_PI  2.0*M_PI *p/PHOTONUM;

    CGFloat h = f + 2.0*M_PI *num/PHOTONUM;

    CGFloat centery = self.view.center.y + 100;

    CGFloat centerx = self.view.center.x;

    CGFloat tmpy =  centery + RADIUS*cos(h);

    CGFloat tmpx = centerx – RADIUS*sin(h);

    view.center = CGPointMake(tmpx,tmpy);

    

    CGPathAddArc(path,nil,self.view.center.x, self.view.center.y + 100,RADIUS,f+ M_PI/2,f+ M_PI/2 + 2.0*M_PI *num/PHOTONUM,0);

    animation.path = path;

    CGPathRelease(path);

    animation.duration = TIME;

    animation.repeatCount = 1;

    animation.calculationMode = @”paced”; 

    return animation;

}

– (NSInteger)getIemViewTag:(NSInteger)tag

{

    

    if (self.currentTag >tag)

    {

        return self.currentTag  – tag;

    }

    else

    {

        return PHOTONUM  – tag + self.currentTag ;

    }

}

@end

#pragma mark – EFItemView

@interface EFItemView ()

@property (nonatomic, strong) NSString *normal;

@property (nonatomic, strong) NSString *highlighted_;

@property (nonatomic, assign) NSInteger tag_;

@property (nonatomic, strong) NSString *title;

@end

@implementation EFItemView

– (instancetype)initWithNormalImage:(NSString *)normal highlightedImage:(NSString *)highlighted tag:(NSInteger)tag title:(NSString *)title

{

    

    self = [super init];

    if (self) {

        _normal = normal;

        _highlighted_ = highlighted;

        _tag_ = tag;

        _title = title;

        [self configViews];

    }

    return self;

}

#pragma mark – configViews

– (void)configViews

{

    

    self.tag = _tag_;

    [self setBackgroundImage:[UIImage imageNamed:_normal] forState:UIControlStateNormal];

    [self setBackgroundImage:[UIImage imageNamed:_highlighted_] forState:UIControlStateHighlighted];

    [self addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];

    [self setTitle:_title forState:UIControlStateNormal];

    [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [self.titleLabel setFont:[UIFont systemFontOfSize:30.0]];

}

– (void)btnTapped:(UIButton *)sender

{

    

    if (self.delegate && [self.delegate respondsToSelector:@selector(didTapped:)])

    {

        [self.delegate didTapped:sender.tag];

    }

}

@end

Download Sample Project From Github

iCarousel Master with Many Examples

iCarouselExampleViewController.h

#import <UIKit/UIKit.h>

#import “iCarousel.h”

@interface iCarouselExampleViewController : UIViewController <iCarouselDataSource, iCarouselDelegate>

@property (nonatomic, strong) IBOutlet iCarousel *carousel;

@property (nonatomic, strong) IBOutlet UINavigationItem *navItem;

@property (nonatomic, strong) IBOutlet UIBarItem *orientationBarItem;

@property (nonatomic, strong) IBOutlet UIBarItem *wrapBarItem;

– (IBAction)switchCarouselType;

– (IBAction)toggleOrientation;

– (IBAction)toggleWrap;

– (IBAction)insertItem;

– (IBAction)removeItem;

@end

iCarouselExampleViewController.m

#import “iCarouselExampleViewController.h”

#pragma GCC diagnostic ignored “-Wgnu”

@interface iCarouselExampleViewController () <UIActionSheetDelegate>

@property (nonatomic, assign) BOOL wrap;

@property (nonatomic, strong) NSMutableArray *items;

@end

@implementation iCarouselExampleViewController

@synthesize carousel;

@synthesize navItem;

@synthesize orientationBarItem;

@synthesize wrapBarItem;

@synthesize wrap;

@synthesize items;

– (void)setUp

{

    //set up data

    self.wrap = YES;

    self.items = [NSMutableArray array];

    for (int i = 0; i < 10; i++)

    {

        [self.items addObject:@(i)];

    }

}

– (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]))

    {

        [self setUp];

    }

    return self;

}

– (id)initWithCoder:(NSCoder *)aDecoder

{

    if ((self = [super initWithCoder:aDecoder]))

    {

        [self setUp];

    }

    return self;

}

– (void)dealloc

{

    //it’s a good idea to set these to nil here to avoid

    //sending messages to a deallocated viewcontroller

    carousel.delegate = nil;

    carousel.dataSource = nil;

    

}

#pragma mark –

#pragma mark View lifecycle

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    //configure carousel

    self.carousel.type = iCarouselTypeCoverFlow2;

    self.navItem.title = @”CoverFlow2″;

}

– (void)viewDidUnload

{

    [super viewDidUnload];

    self.carousel = nil;

    self.navItem = nil;

    self.orientationBarItem = nil;

    self.wrapBarItem = nil;

}

– (BOOL)shouldAutorotateToInterfaceOrientation:(__unused UIInterfaceOrientation)interfaceOrientation

{

    return YES;

}

– (IBAction)switchCarouselType

{

    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@”Select Carousel Type”

                                                       delegate:self

                                              cancelButtonTitle:nil

                                         destructiveButtonTitle:nil

                                              otherButtonTitles:@”Linear”, @”Rotary”, @”Inverted Rotary”, @”Cylinder”, @”Inverted Cylinder”, @”Wheel”, @”Inverted Wheel”, @”CoverFlow”, @”CoverFlow2″, @”Time Machine”, @”Inverted Time Machine”, @”Custom”, nil];

    [sheet showInView:self.view];

}

– (IBAction)toggleOrientation

{

    //carousel orientation can be animated

    [UIView beginAnimations:nil context:nil];

    self.carousel.vertical = !self.carousel.vertical;

    [UIView commitAnimations];

    

    //update button

    self.orientationBarItem.title = self.carousel.vertical? @”Vertical”: @”Horizontal”;

}

– (IBAction)toggleWrap

{

    self.wrap = !self.wrap;

    self.wrapBarItem.title = self.wrap? @”Wrap: ON”: @”Wrap: OFF”;

    [self.carousel reloadData];

}

– (IBAction)insertItem

{

    NSInteger index = MAX(0, self.carousel.currentItemIndex);

    [self.items insertObject:@(self.carousel.numberOfItems) atIndex:(NSUInteger)index];

    [self.carousel insertItemAtIndex:index animated:YES];

}

– (IBAction)removeItem

{

    if (self.carousel.numberOfItems > 0)

    {

        NSInteger index = self.carousel.currentItemIndex;

        [self.items removeObjectAtIndex:(NSUInteger)index];

        [self.carousel removeItemAtIndex:index animated:YES];

    }

}

#pragma mark –

#pragma mark UIActionSheet methods

– (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex

{

    if (buttonIndex >= 0)

    {

        //map button index to carousel type

        iCarouselType type = buttonIndex;

        

        //carousel can smoothly animate between types

        [UIView beginAnimations:nil context:nil];

        self.carousel.type = type;

        [UIView commitAnimations];

        

        //update title

        self.navItem.title = [actionSheet buttonTitleAtIndex:buttonIndex];

    }

}

#pragma mark –

#pragma mark iCarousel methods

– (NSInteger)numberOfItemsInCarousel:(__unused iCarousel *)carousel

{

    return (NSInteger)[self.items count];

}

– (UIView *)carousel:(__unused iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view

{

    UILabel *label = nil;

    

    //create new view if no view is available for recycling

    if (view == nil)

    {

        view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)];

        ((UIImageView *)view).image = [UIImage imageNamed:@”page.png”];

        view.contentMode = UIViewContentModeCenter;

        label = [[UILabel alloc] initWithFrame:view.bounds];

        label.backgroundColor = [UIColor clearColor];

        label.textAlignment = UITextAlignmentCenter;

        label.font = [label.font fontWithSize:50];

        label.tag = 1;

        [view addSubview:label];

    }

    else

    {

        //get a reference to the label in the recycled view

        label = (UILabel *)[view viewWithTag:1];

    }

    

    //set item label

    //remember to always set any properties of your carousel item

    //views outside of the `if (view == nil) {…}` check otherwise

    //you’ll get weird issues with carousel item content appearing

    //in the wrong place in the carousel

    label.text = [self.items[(NSUInteger)index] stringValue];

    

    return view;

}

– (NSInteger)numberOfPlaceholdersInCarousel:(__unused iCarousel *)carousel

{

    //note: placeholder views are only displayed on some carousels if wrapping is disabled

    return 2;

}

– (UIView *)carousel:(__unused iCarousel *)carousel placeholderViewAtIndex:(NSInteger)index reusingView:(UIView *)view

{

    UILabel *label = nil;

    

    //create new view if no view is available for recycling

    if (view == nil)

    {

        //don’t do anything specific to the index within

        //this `if (view == nil) {…}` statement because the view will be

        //recycled and used with other index values later

        view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)];

        ((UIImageView *)view).image = [UIImage imageNamed:@”page.png”];

        view.contentMode = UIViewContentModeCenter;

        

        label = [[UILabel alloc] initWithFrame:view.bounds];

        label.backgroundColor = [UIColor clearColor];

        label.textAlignment = UITextAlignmentCenter;

        label.font = [label.font fontWithSize:50.0f];

        label.tag = 1;

        [view addSubview:label];

    }

    else

    {

        //get a reference to the label in the recycled view

        label = (UILabel *)[view viewWithTag:1];

    }

    

    //set item label

    //remember to always set any properties of your carousel item

    //views outside of the `if (view == nil) {…}` check otherwise

    //you’ll get weird issues with carousel item content appearing

    //in the wrong place in the carousel

    label.text = (index == 0)? @”[“: @”]”;

    

    return view;

}

– (CATransform3D)carousel:(__unused iCarousel *)carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform

{

    //implement ‘flip3D’ style carousel

    transform = CATransform3DRotate(transform, M_PI / 8.0f, 0.0f, 1.0f, 0.0f);

    return CATransform3DTranslate(transform, 0.0f, 0.0f, offset * self.carousel.itemWidth);

}

– (CGFloat)carousel:(__unused iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value

{

    //customize carousel display

    switch (option)

    {

        case iCarouselOptionWrap:

        {

            //normally you would hard-code this to YES or NO

            return self.wrap;

        }

        case iCarouselOptionSpacing:

        {

            //add a bit of spacing between the item views

            return value * 1.05f;

        }

        case iCarouselOptionFadeMax:

        {

            if (self.carousel.type == iCarouselTypeCustom)

            {

                //set opacity based on distance from camera

                return 0.0f;

            }

            return value;

        }

        case iCarouselOptionShowBackfaces:

        case iCarouselOptionRadius:

        case iCarouselOptionAngle:

        case iCarouselOptionArc:

        case iCarouselOptionTilt:

        case iCarouselOptionCount:

        case iCarouselOptionFadeMin:

        case iCarouselOptionFadeMinAlpha:

        case iCarouselOptionFadeRange:

        case iCarouselOptionOffsetMultiplier:

        case iCarouselOptionVisibleItems:

        {

            return value;

        }

    }

}

#pragma mark –

#pragma mark iCarousel taps

– (void)carousel:(__unused iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index

{

    NSNumber *item = (self.items)[(NSUInteger)index];

    NSLog(@”Tapped view number: %@”, item);

}

– (void)carouselCurrentItemIndexDidChange:(__unused iCarousel *)carousel

{

    NSLog(@”Index: %@”, @(self.carousel.currentItemIndex));

}

@end

iCarouselExampleAppDelegate.h

#import <UIKit/UIKit.h>

@class iCarouselExampleViewController;

@interface iCarouselExampleAppDelegate : NSObject <UIApplicationDelegate>

@property (nonatomic, strong) IBOutlet UIWindow *window;

@property (nonatomic, strong) IBOutlet iCarouselExampleViewController *viewController;

@end

iCarouselExampleAppDelegate.m

#import “iCarouselExampleAppDelegate.h”

#import “iCarouselExampleViewController.h”

@implementation iCarouselExampleAppDelegate

@synthesize window;

@synthesize viewController;

– (BOOL)application:(__unused UIApplication *)application didFinishLaunchingWithOptions:(__unused NSDictionary *)launchOptions

{

    [self.window addSubview:self.viewController.view];

    [self.window makeKeyAndVisible];

    return YES;

}

@end

Download Sample Project From Github

Google Plus Login And Share

Referace From ::  https://developers.google.com/+/mobile/ios/getting-started

https://developers.google.com/+/mobile/ios/share/

 

ViewController.h

#import <UIKit/UIKit.h>

#import <GooglePlus/GooglePlus.h>

@class GPPSignInButton;

@interface ViewController : UIViewController <GPPSignInDelegate>

{

    

}

@property (weak, nonatomic) IBOutlet GPPSignInButton *signInButton;

– (IBAction) didTapShare: (id)sender;

@end

ViewController.m

#import “ViewController.h”

#import <GoogleOpenSource/GoogleOpenSource.h>

#import <GooglePlus/GooglePlus.h>

#define CLIEND_ID @“98223363200-tteph5459h1qve2js1o3vb4jqeegcghg.apps.googleusercontent.com” //add your Google Plus ClientID here

#define GOOGLE_PLUS_CLIEND_ID @“440607175691-4bhfdefg7sbkrrjk3mp9t5dc15upiet0.apps.googleusercontent.com”

static NSString * const kClientId = CLIEND_ID;

@interface ViewController ()

@end

@implementation ViewController

@synthesize signInButton;

– (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    GPPSignIn *signIn = [GPPSignIn sharedInstance];

    signIn.shouldFetchGooglePlusUser = YES;

    signIn.shouldFetchGoogleUserEmail = YES;  // Uncomment to get the user’s email

    

    // You previously set kClientId in the “Initialize the Google+ client” step

    signIn.clientID = kClientId;

    

    [GPPSignIn sharedInstance].actions = [NSArray arrayWithObjects:

                                          @”http://schemas.google.com/AddActivity&#8221;,

                                          @”http://schemas.google.com/BuyActivity&#8221;,

                                          @”http://schemas.google.com/CheckInActivity&#8221;,

                                          @”http://schemas.google.com/CommentActivity&#8221;,

                                          @”http://schemas.google.com/CreateActivity&#8221;,

                                          @”http://schemas.google.com/ListenActivity&#8221;,

                                          @”http://schemas.google.com/ReserveActivity&#8221;,

                                          @”http://schemas.google.com/ReviewActivity&#8221;,

                                          nil];

    

    // Uncomment one of these two statements for the scope you chose in the previous step

    signIn.scopes = @[ kGTLAuthScopePlusLogin ];  // “https://www.googleapis.com/auth/plus.login” scope

    //signIn.scopes = @[ @”profile” ];            // “profile” scope

    

    // Optional: declare signIn.actions, see “app activities”

    signIn.delegate = self;

    

    

    [signIn trySilentAuthentication];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (void)finishedWithAuth: (GTMOAuth2Authentication *)auth

                   error: (NSError *) error

{

    NSLog(@”Received error %@ and auth object %@”,error, auth);

    if (error) {

        // Do some error handling here.

    } else {

        NSLog(@”%@ %@”,[GPPSignIn sharedInstance].userEmail, [GPPSignIn sharedInstance].userID);

        [self refreshInterfaceBasedOnSignIn];

    }

}

-(void)refreshInterfaceBasedOnSignIn

{

    if ([[GPPSignIn sharedInstance] authentication]) {

        // The user is signed in.

        self.signInButton.hidden = YES;

        // Perform other actions here, such as showing a sign-out button

    } else {

        self.signInButton.hidden = NO;

        // Perform other actions here

    }

}

// Share Code

– (IBAction) didTapShare: (id)sender {

    id<GPPNativeShareBuilder> shareBuilder = [[GPPShare sharedInstance] nativeShareDialog];

    

    // This line will fill out the title, description, and thumbnail from

    // the URL that you are sharing and includes a link to that URL.

    [shareBuilder setURLToShare:[NSURL URLWithString:@”https://www.shinnxstudios.com&#8221;]];

    [shareBuilder setPrefillText:@”This is an awesome G+ Sample to share”];

   // [shareBuilder setTitle:@”Title” description:@”Descp” thumbnailURL:[NSURL URLWithString:@”https://www.fbo.com/imageurl“]];

    

    [shareBuilder open];

}

// For Signout USe this code

– (void)signOut {

    [[GPPSignIn sharedInstance] signOut];

}

// Disconnet User

– (void)disconnect {

    [[GPPSignIn sharedInstance] disconnect];

}

– (void)didDisconnectWithError:(NSError *)error {

    if (error) {

        NSLog(@”Received error %@”, error);

    } else {

        // The user is signed out and disconnected.

        // Clean up user data as specified by the Google+ terms.

    }

}

@end

Download Sample Project From Github

Download Google Plus iOS SDK

Custom TableView With Searchbar And Expandable TableView

MCCallVendorsController.h

#import <UIKit/UIKit.h>

#import “ZJSwitch.h”

@interface MCCallVendorsController : UIViewController

@property (strong, nonatomic) NSString *moveTo;

@property  (strong, nonatomic) NSString *moveFrom;

@property (strong, nonatomic) NSArray *arrayJson;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

//@property (weak, nonatomic) IBOutlet UISwitch *switchMoveFromTo;

@property (weak, nonatomic) IBOutlet UIView *viewForSwitch;

@end

MCCallVendorsController.m

#import “MCCallVendorsController.h”

#import “MCCallVendorVendorCell.h”

#import “MCCallVendorVendorModel.h”

#import “MCCallVendorTaskCell.h”

#import “MCCallVendorTaskModel.h”

#import “Utility.h”

//#import “MCNetworkManager.h”

#import “MCVendorsListController.h”

NSString *const filterTaskConstant = @”%K CONTAINS[c] %@”;

NSString *const vendorCell = @”vendorCell”;

NSString *const viewMore = @”viewMore”;

NSString *const taskSectionCell = @”taskSectionCell”;

NSString *const placeholderText = @”Search:moving, packing”;

NSString *const vendorsListControllerName = @”MCVendorsListController”;

typedef enum

{

    MCVendorTypeFrom,

    MCVendorTypeTo

}MCVendorType;

@interface MCCallVendorsController ()<UITableViewDataSource,UITableViewDelegate,MCCallVendorTaskCellProtocol , MCCallVendorVendorCellProtocol,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (nonatomic, strong) NSMutableArray *fromModelArray;

@property (nonatomic, strong) NSMutableArray *toModelArray;

@property (nonatomic, strong) NSArray *modelArray;

@property (nonatomic, assign) MCVendorType vendorType;

@property (weak, nonatomic) IBOutlet UITableView *taskVendorsTableView;

@end

@implementation MCCallVendorsController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    [self.activityIndicator startAnimating];

    self.navigationController.navigationBarHidden = YES;

    self.vendorType = MCVendorTypeFrom;

    [self loadModels];

    UIColor *color = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];

    self.searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

    

    

    CGFloat r1 = CGRectGetHeight(self.viewForSwitch.bounds) / 2.0;

    self.viewForSwitch.layer.cornerRadius = r1;

    

    ZJSwitch *switchMoveFromTo = [[ZJSwitch alloc] initWithFrame:CGRectMake(2, 2, self.viewForSwitch.frame.size.width4, self.viewForSwitch.frame.size.height4)];

    switchMoveFromTo.on = NO;

    switchMoveFromTo.backgroundColor = [UIColor clearColor];

    switchMoveFromTo.onTintColor = [UIColor colorWithRed:37/255.0 green:81/255.0 blue:92/255.0 alpha:1];

    switchMoveFromTo.offTintColor = [UIColor colorWithRed:37/255.0 green:81/255.0 blue:92/255.0 alpha:1];

    switchMoveFromTo.textColor = [UIColor blackColor];

    switchMoveFromTo.onText = @”Moving To”;

    switchMoveFromTo.offText = @”Moving From”;

    //switch2.textFont = @””;

    [switchMoveFromTo setOnTextFontSize:7];

    [switchMoveFromTo setOffTextFontSize:7];

    [switchMoveFromTo addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitch addSubview:switchMoveFromTo];

    

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    

    //sample data

    

    // Dispose of any resources that can be recreated.

}

– (void)loadModels

{

    

    NSDictionary *dictionary = @{

                                 @”moveTo”: @”11111″,

                                 @”moveFrom”:@”22222″

                                 };

    

//    [[MCNetworkManager sharedNetworkManager] getVendorsList:dictionary withCompletionBlock:^(NSDictionary *response, NSError *error) {

//        NSLog(@”Response”);

//        NSArray *moveFromArray = response[@”result”][@”move_from”][@”tasks”];

//        NSArray *moveToArray = response[@”result”][@”move_to”][@”tasks”];

//        self.fromModelArray = [NSMutableArray array];

//        self.toModelArray = [NSMutableArray array];

//        [self generateVendorsModelsForArray:moveFromArray moveIntoArray:self.fromModelArray];

//        [self generateVendorsModelsForArray:moveToArray moveIntoArray:self.toModelArray];

//        self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

//        [self.taskVendorsTableView reloadData];

//        [self.activityIndicator stopAnimating];

//        self.activityIndicator.hidden = YES;

//    }];

    

    

    

    self.arrayJson = [Utility parseStatesResponseFileName:@”Json_File” FileType:@”json”];

    NSLog(@”%@”,self.arrayJson);

    

    NSDictionary *response = (NSDictionary *)self.arrayJson;

    

    NSArray *moveFromArray = response[@”result”][@”move_from”][@”tasks”];

            NSArray *moveToArray = response[@”result”][@”move_to”][@”tasks”];

            self.fromModelArray = [NSMutableArray array];

            self.toModelArray = [NSMutableArray array];

            [self generateVendorsModelsForArray:moveFromArray moveIntoArray:self.fromModelArray];

            [self generateVendorsModelsForArray:moveToArray moveIntoArray:self.toModelArray];

            self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

            [self.taskVendorsTableView reloadData];

            [self.activityIndicator stopAnimating];

            self.activityIndicator.hidden = YES;

}

     

     

– (void)generateVendorsModelsForArray:(NSArray *)array moveIntoArray:(NSMutableArray *)movingArray

{

         for(NSDictionary *taskWithVedorsList in array)

         {

             MCCallVendorTaskModel *model = [[MCCallVendorTaskModel alloc] init];

             //set task and vendors list details

             [model setDataFromDictionary:taskWithVedorsList];

             model.expanded = NO;

             [movingArray addObject:model];

         }

}

– (IBAction)switchStateChanged:(id)sender

{

    UISwitch *toFromswitch = (UISwitch *)sender;

    self.vendorType  = (toFromswitch.isOn) ? MCVendorTypeFrom : MCVendorTypeTo;

    [self filterTasks:self.searchTextField.text];

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    MCCallVendorTaskModel *taskModel = self.modelArray[section];

    NSInteger rows = (taskModel.expanded) ? ((taskModel.vendorsArray.count > 5) ? 6 : taskModel.vendorsArray.count) : 0;

    return rows;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *identifier = vendorCell;

    MCCallVendorTaskModel *model = self.modelArray[indexPath.section];

    NSArray *vendorsArray = model.vendorsArray;

    if(indexPath.row > 4 && vendorsArray.count > 5)

    {

        identifier = viewMore;

    }

    MCCallVendorVendorCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    cell.delegate = self;

    cell.section = indexPath.section;

    cell.model = vendorsArray[indexPath.row];

    

    if([identifier isEqualToString:vendorCell])

    {

        //check if last cell and vendor cell

        if((indexPath.row == vendorsArray.count1))

        {

            dispatch_async(dispatch_get_main_queue(), ^{

                UIBezierPath *maskPath;

                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                                 byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                       cornerRadii:CGSizeMake(5.0, 5.0)];

                

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

                maskLayer.path = maskPath.CGPath;

                maskLayer.frame = cell.bounds;

                cell.layer.mask = maskLayer;

                cell.separator.hidden = YES;

            });

        }

        else

        {

            dispatch_async(dispatch_get_main_queue(), ^{

                UIBezierPath *maskPath;

                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                                 byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                       cornerRadii:CGSizeMake(0.0, 0.0)];

                

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

                maskLayer.path = maskPath.CGPath;

                maskLayer.frame = cell.bounds;

                cell.layer.mask = maskLayer;

                if((indexPath.row > 3 && vendorsArray.count > 5))

                {

                    cell.separator.hidden = YES;

                }

                else

                {

                    cell.separator.hidden = NO;

                }

            });

        }

       

    }

    else if ([identifier isEqualToString:viewMore])

    {

        dispatch_async(dispatch_get_main_queue(), ^{

            UIBezierPath *maskPath;

            maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                             byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                   cornerRadii:CGSizeMake(5.0, 5.0)];

            

            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

            maskLayer.path = maskPath.CGPath;

            maskLayer.frame = cell.bounds;

            cell.layer.mask = maskLayer;

        });

    }

    

    return cell;

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return self.modelArray.count;

}

– (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{

    MCCallVendorTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:taskSectionCell];

    cell.delegate = self;

    cell.model = self.modelArray[section];

    dispatch_async(dispatch_get_main_queue(), ^{

        UIBezierPath *maskPath;

        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                         byRoundingCorners:(UIRectCornerTopRight|UIRectCornerTopLeft)

                                               cornerRadii:CGSizeMake(5.0, 5.0)];

        

        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

        maskLayer.path = maskPath.CGPath;

        maskLayer.frame = cell.bounds;

        cell.layer.mask = maskLayer;

    });

    return cell;

}

– (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section

{

    return 20.0;

}

– (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section

{

    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];

    view.backgroundColor = [UIColor clearColor];

    return  view;

}

#pragma mark – Task cell delegates –

– (void)expandCell:(MCCallVendorTaskCell *)cell

{

    for(int i=0; i< self.modelArray.count ; i++)

    {

        MCCallVendorTaskModel *model = self.modelArray[i];

        if(model != cell.model)

        {

            model.expanded = NO;

        }

    }

    cell.model.expanded = !(cell.model.expanded);

    [self.taskVendorsTableView reloadData];

}

#pragma  mark – Vendor cell delegates –

– (void)tappedViewMore:(MCCallVendorVendorCell *)cell

{

    //push a new controller

    MCVendorsListController *vendorsListController = [[UIStoryboard storyboardWithName:vendorsListControllerName bundle:nil] instantiateInitialViewController];

    //pass the selected vendors list,this a a parcular vendor cell, but we need to get list of the vendors for that section

    vendorsListController.model = self.modelArray[cell.section];

    [self.navigationController pushViewController:vendorsListController animated:YES];

}

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell

{

    //call the vendor

    [Utility makeCall:cell.model.vendorPhone];

}

– (IBAction)searchTasks:(id)sender

{

    NSString *textToSearch = ((UITextField *)sender).text ;

    [self filterTasks:textToSearch];

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [self.view endEditing:YES];

    return YES;

}

– (void)filterTasks:(NSString *)filterText

{

    NSLog(@”%@”,filterText);

    if(filterText.length)

    {

        NSArray *taskVendorArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

        NSString* filter =  filterTaskConstant;

        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, @”taskName”,filterText];

        NSArray* filteredData = [taskVendorArray filteredArrayUsingPredicate:predicate];

        //filtered Data

        self.modelArray = filteredData;

        NSLog(@”Filtered Data”);

        [self.taskVendorsTableView reloadData];

    }

    else

    {

        self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

        [self.taskVendorsTableView reloadData];

    }

}

– (IBAction)tapGesture:(id)sender

{

    [self.view endEditing:YES];

}

@end

MCCallVendorTaskCell.h

#import <UIKit/UIKit.h>

#import “MCCallVendorTaskModel.h”

@class MCCallVendorTaskCell;

@protocol MCCallVendorTaskCellProtocol <NSObject>

– (void)expandCell:(MCCallVendorTaskCell *)cell;

@end

@interface MCCallVendorTaskCell : UITableViewCell

@property (nonatomic, strong) MCCallVendorTaskModel *model;

@property (nonatomic, assign) id <MCCallVendorTaskCellProtocol> delegate;

@end

MCCallVendorTaskCell.m

#import “MCCallVendorTaskCell.h”

@interface MCCallVendorTaskCell()

@property (weak, nonatomic) IBOutlet UILabel *taskName;

@property (weak, nonatomic) IBOutlet UIButton *expandButton;

@end

@implementation MCCallVendorTaskCell

– (IBAction)expandButtonAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(expandCell:)])

    {

        [self.delegate expandCell:self];

        [self updateButtonState];

    }

}

– (void)setModel:(MCCallVendorTaskModel *)model

{

    _model = model;

    self.taskName.text = _model.taskName;

    [self updateButtonState];

}

– (void)updateButtonState

{

    if(self.model.expanded)

    {

        [self.expandButton setBackgroundImage:[UIImage imageNamed:@”drop-up”] forState:UIControlStateNormal];

    }

    else

    {

        [self.expandButton setBackgroundImage:[UIImage imageNamed:@”drop-down”] forState:UIControlStateNormal];

    }

}

@end

MCCallVendorTaskModel.h

#import <Foundation/Foundation.h>

#import “MCCallVendorVendorModel.h”

@interface MCCallVendorTaskModel : NSObject

@property (nonatomic, assign) BOOL expanded;

@property (nonatomic, strong) NSString *taskName;

@property (nonatomic, strong) NSMutableArray *vendorsArray; // of type vendors model

– (void)setDataFromDictionary:(NSDictionary *)dictionary;

@end

MCCallVendorTaskModel.m

#import “MCCallVendorTaskModel.h”

@implementation MCCallVendorTaskModel

– (void)setDataFromDictionary:(NSDictionary *)dictionary

{

    self.taskName = dictionary[@”name”];

    //vendors

    self.vendorsArray = [NSMutableArray array];

    NSArray *vendorsArray = dictionary[@”vendors”];

    for(NSDictionary *vendorDictionay in vendorsArray )

    {

        MCCallVendorVendorModel *vendorModel = [[MCCallVendorVendorModel alloc] init];

        [vendorModel setDataFromDictionary:vendorDictionay];

        [self.vendorsArray addObject:vendorModel];

    }

}

@end

MCCallVendorVendorCell.h

#import <UIKit/UIKit.h>

#import “MCCallVendorVendorModel.h”

@class MCCallVendorVendorCell;

@protocol MCCallVendorVendorCellProtocol <NSObject>

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell;

@optional

– (void)tappedViewMore:(MCCallVendorVendorCell *)cell;

@end

@interface MCCallVendorVendorCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIView *separator;

@property (nonatomic, weak) id <MCCallVendorVendorCellProtocol> delegate;

@property (nonatomic, strong) MCCallVendorVendorModel *model;

@property (nonatomic, assign) NSUInteger section;

@end

MCCallVendorVendorCell.m

#import “MCCallVendorVendorCell.h”

@interface MCCallVendorVendorCell ()

@property (weak, nonatomic) IBOutlet UILabel *vendorName;

@end

@implementation MCCallVendorVendorCell

– (void)setModel:(MCCallVendorVendorModel *)model

{

    _model = model;

    self.vendorName.text = _model.vendorName;

}

– (IBAction)callVendorAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(tappedCallVendor:)])

    {

        [self.delegate tappedCallVendor:self];

    }

}

– (IBAction)viewMoreAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(tappedViewMore:)])

    {

        [self.delegate tappedViewMore:self];

    }

}

@end

MCCallVendorVendorModel.h

#import <Foundation/Foundation.h>

@interface MCCallVendorVendorModel : NSObject

@property (nonatomic, strong) NSString *vendorName;

@property (nonatomic, strong) NSString *vendorPhone;

– (void)setDataFromDictionary:(NSDictionary *)dictionary;

@end

#import “MCCallVendorVendorModel.h”

@implementation MCCallVendorVendorModel

– (void)setDataFromDictionary:(NSDictionary *)dictionary

{

    self.vendorName = dictionary[@”name”];

    self.vendorPhone = dictionary[@”phone”];

}

@end

MCVendorsListController.h

#import <UIKit/UIKit.h>

#import “MCCallVendorTaskModel.h”

@interface MCVendorsListController : UIViewController

@property (nonatomic, strong) MCCallVendorTaskModel *model; // task model with name and list of vendors

@end

MCVendorsListController.m

#import “MCVendorsListController.h”

#import “MCCallVendorVendorCell.h”

#import “Utility.h”

NSString *const vendorsFilterString =  @”%K CONTAINS[c] %@”;

NSString *const vendorCellIdentifier = @”vendorCell”;

@interface MCVendorsListController()<UITableViewDataSource, UITableViewDelegate , MCCallVendorVendorCellProtocol>

@property (weak, nonatomic) IBOutlet UITableView *vendorsTableView;

@property (nonatomic, strong) NSArray *modelsArray;

@end

@implementation MCVendorsListController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.navigationController.navigationBarHidden = YES;

    [self loadAllVendors];

}

– (void)loadAllVendors

{

    self.modelsArray = self.model.vendorsArray;

    [self.vendorsTableView reloadData];

}

– (IBAction)backButtonAction:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.modelsArray.count;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    MCCallVendorVendorCell *cell = [tableView dequeueReusableCellWithIdentifier:vendorCellIdentifier];

    cell.model = self.modelsArray[indexPath.row];

    cell.delegate = self;

    return cell;

}

– (IBAction)searchVendors:(id)sender

{

    NSString *textToSearch = ((UITextField *)sender).text ;

    NSLog(@”%@”,textToSearch);

    if(textToSearch.length)

    {

        NSArray *taskVendorArray = self.model.vendorsArray;

        NSString* filter = vendorsFilterString;

        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, @”vendorName”,textToSearch];

        NSArray* filteredData = [taskVendorArray filteredArrayUsingPredicate:predicate];

        //filtered Data

        self.modelsArray = filteredData;

        NSLog(@”Filtered Data”);

        [self.vendorsTableView reloadData];

    }

    else

    {

        self.modelsArray = self.model.vendorsArray;

        [self.vendorsTableView reloadData];

    }

}

#pragma mark – vendor cell delegates –

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell

{

    [Utility makeCall:cell.model.vendorPhone];

}

@end

ZJSwitch.h

#import <UIKit/UIKit.h>

@interface ZJSwitch : UIControl

@property (nonatomic, assign, getter = isOn) BOOL on;

@property (nonatomic, strong) UIColor *onTintColor;

@property (nonatomic, strong) UIColor *offTintColor;

@property (nonatomic, strong) UIColor *thumbTintColor;

@property (nonatomic, strong) UIColor *textColor;

@property (nonatomic, strong) UIFont *textFont;

@property (nonatomic, strong) NSString *onText;

@property (nonatomic, strong) NSString *offText;

– (void)setTextFont:(UIFont *)textFont;

– (void)setOnTextFontSize:(CGFloat)onTextFontSize;

– (void)setOffTextFontSize:(CGFloat)offTextFontSize;

– (void)setOn:(BOOL)on animated:(BOOL)animated;

@end

ZJSwitch.m

#import “ZJSwitch.h”

#define ZJSwitchMaxHeight 100.0f

#define ZJSwitchMinHeight 20.0f

#define ZJSwitchMinWidth 30.0f

#define ZJSwitchKnobSize 16.0f

@interface ZJSwitch ()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UIView *onContentView;

@property (nonatomic, strong) UIView *offContentView;

@property (nonatomic, strong) UIView *knobView;

@property (nonatomic, strong) UILabel *onLabel;

@property (nonatomic, strong) UILabel *offLabel;

– (void)commonInit;

– (CGRect)roundRect:(CGRect)frameOrBounds;

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer;

– (void)handlePanGestureRecognizerEvent:(UIPanGestureRecognizer *)recognizer;

@end

@implementation ZJSwitch

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:[self roundRect:frame]];

    if (self) {

        [self commonInit];

    }

    return self;

}

– (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super initWithCoder:aDecoder];

    

    if (self) {

        [self commonInit];

    }

    

    return self;

}

– (void)setBounds:(CGRect)bounds

{

    [super setBounds:[self roundRect:bounds]];

    

    [self setNeedsLayout];

}

– (void)setFrame:(CGRect)frame

{

    [super setFrame:[self roundRect:frame]];

    

    [self setNeedsLayout];

}

– (void)setTextFont:(UIFont *)textFont

{

    _onLabel.font = textFont;

    _offLabel.font = textFont;

    

}

– (void)setOnText:(NSString *)onText

{

    if (_onText != onText) {

        _onText = onText;

        

        _onLabel.text = onText;

    }

}

– (void)setOffText:(NSString *)offText

{

    if (_offText != offText) {

        _offText = offText;

        

        _offLabel.text = offText;

    }

}

– (void)setOnTextFontSize:(CGFloat)onTextFontSize

{

    [_onLabel setFont:[UIFont systemFontOfSize:onTextFontSize]];

    

}

– (void)setOffTextFontSize:(CGFloat)offTextFontSize

{

     [_offLabel setFont:[UIFont systemFontOfSize:offTextFontSize]];

}

– (void)setOnTintColor:(UIColor *)onTintColor

{

    if (_onTintColor != onTintColor) {

        _onTintColor = onTintColor;

        

        _onContentView.backgroundColor = onTintColor;

    }

}

– (void)setOffTintColor:(UIColor *)offTintColor

{

    if (_offTintColor != offTintColor) {

        _offTintColor = offTintColor;

        

        _offContentView.backgroundColor = offTintColor;

    }

}

– (void)setThumbTintColor:(UIColor *)thumbTintColor

{

    if (_thumbTintColor != thumbTintColor) {

        _thumbTintColor = thumbTintColor;

        

        _knobView.backgroundColor = _thumbTintColor;

    }

}

– (void)layoutSubviews

{

    [super layoutSubviews];

    

    self.containerView.frame = self.bounds;

    

    CGFloat r = CGRectGetHeight(self.containerView.bounds) / 2.0;

    

    self.containerView.layer.cornerRadius = r;

    self.containerView.layer.masksToBounds = YES;

    

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    

    if (!self.isOn) {

        // frame of off status

        self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                              0,

                                              CGRectGetWidth(self.containerView.bounds),

                                              CGRectGetHeight(self.containerView.bounds));

        

        self.offContentView.frame = CGRectMake(0,

                                               0,

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetHeight(self.containerView.bounds));

        

        self.knobView.frame = CGRectMake(margin,

                                         margin,

                                         ZJSwitchKnobSize,

                                         ZJSwitchKnobSize);

    } else {

        // frame of on status

        self.onContentView.frame = CGRectMake(0,

                                              0,

                                              CGRectGetWidth(self.containerView.bounds),

                                              CGRectGetHeight(self.containerView.bounds));

        

        self.offContentView.frame = CGRectMake(0,

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetHeight(self.containerView.bounds));

        

        self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                         margin,

                                         ZJSwitchKnobSize,

                                         ZJSwitchKnobSize);

    }

    

    CGFloat lHeight = 20.0f;

    CGFloat lMargin = r – (sqrtf(powf(r, 2) – powf(lHeight / 2.0, 2))) + margin;

    

    self.onLabel.frame = CGRectMake(lMargin – 2,

                                    r – lHeight / 2.0,

                                    CGRectGetWidth(self.onContentView.bounds) – lMargin – ZJSwitchKnobSize2 * margin + 1,

                                    lHeight);

    self.onLabel.textAlignment = NSTextAlignmentCenter;

    

    

    

    self.offLabel.frame = CGRectMake(ZJSwitchKnobSize + 2 * margin – 1,

                                     r – lHeight / 2.0,

                                     CGRectGetWidth(self.onContentView.bounds) – lMargin – ZJSwitchKnobSize2 * margin + 7,

                                     lHeight);

    self.offLabel.textAlignment = NSTextAlignmentCenter;

  

}

– (void)setOn:(BOOL)on

{

    [self setOn:on animated:NO];

}

– (void)setOn:(BOOL)on animated:(BOOL)animated

{

    if (_on == on) {

        return;

    }

    

    _on = on;

    

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    

    if (!animated) {

        if (!self.isOn) {

            // frame of off status

            self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                                  0,

                                                  CGRectGetWidth(self.containerView.bounds),

                                                  CGRectGetHeight(self.containerView.bounds));

            

            self.offContentView.frame = CGRectMake(0,

                                                   0,

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetHeight(self.containerView.bounds));

            

            self.knobView.frame = CGRectMake(margin,

                                             margin,

                                             ZJSwitchKnobSize,

                                             ZJSwitchKnobSize);

        } else {

            // frame of on status

            self.onContentView.frame = CGRectMake(0,

                                                  0,

                                                  CGRectGetWidth(self.containerView.bounds),

                                                  CGRectGetHeight(self.containerView.bounds));

            

            self.offContentView.frame = CGRectMake(0,

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetHeight(self.containerView.bounds));

            

            self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                             margin,

                                             ZJSwitchKnobSize,

                                             ZJSwitchKnobSize);

        }

    } else {

        if (self.isOn) {

            [UIView animateWithDuration:0.25

                             animations:^{

                                 self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                                                  margin,

                                                                  ZJSwitchKnobSize,

                                                                  ZJSwitchKnobSize);

                             }

                             completion:^(BOOL finished){

                                 self.onContentView.frame = CGRectMake(0,

                                                                       0,

                                                                       CGRectGetWidth(self.containerView.bounds),

                                                                       CGRectGetHeight(self.containerView.bounds));

                                 

                                 self.offContentView.frame = CGRectMake(0,

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetHeight(self.containerView.bounds));

                             }];

        } else {

            [UIView animateWithDuration:0.25

                             animations:^{

                                 self.knobView.frame = CGRectMake(margin,

                                                                  margin,

                                                                  ZJSwitchKnobSize,

                                                                  ZJSwitchKnobSize);

                             }

                             completion:^(BOOL finished){

                                 self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                                                       0,

                                                                       CGRectGetWidth(self.containerView.bounds),

                                                                       CGRectGetHeight(self.containerView.bounds));

                                 

                                 self.offContentView.frame = CGRectMake(0,

                                                                        0,

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetHeight(self.containerView.bounds));

                             }];

        }

    }

    

    [self sendActionsForControlEvents:UIControlEventValueChanged];

}

#pragma mark – Private API

– (void)commonInit

{

    self.backgroundColor = [UIColor clearColor];

    

    _onTintColor = [UIColor colorWithRed:130 / 255.0 green:200 / 255.0 blue:90 / 255.0 alpha:1.0];

    _offTintColor = [UIColor colorWithWhite:0.75 alpha:1.0];

    _thumbTintColor = [UIColor colorWithWhite:1.0 alpha:1.0];

    

    _textFont = [UIFont systemFontOfSize:10.0f];

    _textColor = [UIColor whiteColor];

    

    _containerView = [[UIView alloc] initWithFrame:self.bounds];

    _containerView.backgroundColor = [UIColor clearColor];

    [self addSubview:_containerView];

    

    _onContentView = [[UIView alloc] initWithFrame:self.bounds];

    _onContentView.backgroundColor = _onTintColor;

    [_containerView addSubview:_onContentView];

    

    _offContentView = [[UIView alloc] initWithFrame:self.bounds];

    _offContentView.backgroundColor = _offTintColor;

    [_containerView addSubview:_offContentView];

    

    _knobView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZJSwitchKnobSize, ZJSwitchKnobSize)];

    _knobView.backgroundColor = _thumbTintColor;

    _knobView.layer.cornerRadius = (ZJSwitchKnobSize / 2.0);

    [_containerView addSubview:_knobView];

    

    _onLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    _onLabel.backgroundColor = [UIColor clearColor];

    _onLabel.textAlignment = NSTextAlignmentCenter;

    _onLabel.textColor = _textColor;

    _onLabel.font = _textFont;

    _onLabel.text = _onText;

    [_onContentView addSubview:_onLabel];

    

    _offLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    _offLabel.backgroundColor = [UIColor clearColor];

    _offLabel.textAlignment = NSTextAlignmentCenter;

    _offLabel.textColor = _textColor;

    _offLabel.font = _textFont;

    _offLabel.text = _offText;

    [_offContentView addSubview:_offLabel];

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self addGestureRecognizer:tapGesture];

    

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handlePanGestureRecognizerEvent:)];

    [self addGestureRecognizer:panGesture];

}

– (CGRect)roundRect:(CGRect)frameOrBounds

{

    CGRect newRect = frameOrBounds;

    

    if (newRect.size.height > ZJSwitchMaxHeight) {

        newRect.size.height = ZJSwitchMaxHeight;

    }

    

    if (newRect.size.height < ZJSwitchMinHeight) {

        newRect.size.height = ZJSwitchMinHeight;

    }

    

    if (newRect.size.width < ZJSwitchMinWidth) {

        newRect.size.width = ZJSwitchMinWidth;

    }

    

    return newRect;

}

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    if (recognizer.state == UIGestureRecognizerStateEnded) {

        [self setOn:!self.isOn animated:NO];

    }

}

– (void)handlePanGestureRecognizerEvent:(UIPanGestureRecognizer *)recognizer

{

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    CGFloat offset = 6.0f;

    

    switch (recognizer.state) {

        case UIGestureRecognizerStateBegan:{

            if (!self.isOn) {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(margin,

                                                                      margin,

                                                                      ZJSwitchKnobSize + offset,

                                                                      ZJSwitchKnobSize);

                                 }];

            } else {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – (ZJSwitchKnobSize + offset),

                                                                      margin,

                                                                      ZJSwitchKnobSize + offset,

                                                                      ZJSwitchKnobSize);

                                 }];

            }

            break;

        }

        case UIGestureRecognizerStateCancelled:

        case UIGestureRecognizerStateFailed: {

            if (!self.isOn) {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(margin,

                                                                      margin,

                                                                      ZJSwitchKnobSize,

                                                                      ZJSwitchKnobSize);

                                 }];

            } else {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – ZJSwitchKnobSize,

                                                                      margin,

                                                                      ZJSwitchKnobSize,

                                                                      ZJSwitchKnobSize);

                                 }];

            }

            break;

        }

        case UIGestureRecognizerStateChanged:{

            break;

        }

        case UIGestureRecognizerStateEnded:

            [self setOn:!self.isOn animated:YES];

            break;

        case UIGestureRecognizerStatePossible:

            break;

    }

}

@end

Download Sample Project From Github

UITableView with Custom Switch

MCCallVendorsController.h

#import <UIKit/UIKit.h>

#import “ZJSwitch.h”

@interface MCCallVendorsController : UIViewController

@property (strong, nonatomic) NSString *moveTo;

@property  (strong, nonatomic) NSString *moveFrom;

@property (strong, nonatomic) NSArray *arrayJson;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

//@property (weak, nonatomic) IBOutlet UISwitch *switchMoveFromTo;

@property (weak, nonatomic) IBOutlet UIView *viewForSwitch;

@end

MCCallVendorsController.m

#import “MCCallVendorsController.h”

#import “MCCallVendorVendorCell.h”

#import “MCCallVendorVendorModel.h”

#import “MCCallVendorTaskCell.h”

#import “MCCallVendorTaskModel.h”

#import “Utility.h”

//#import “MCNetworkManager.h”

#import “MCVendorsListController.h”

NSString *const filterTaskConstant = @”%K CONTAINS[c] %@”;

NSString *const vendorCell = @”vendorCell”;

NSString *const viewMore = @”viewMore”;

NSString *const taskSectionCell = @”taskSectionCell”;

NSString *const placeholderText = @”Search:moving, packing”;

NSString *const vendorsListControllerName = @”MCVendorsListController”;

typedef enum

{

    MCVendorTypeFrom,

    MCVendorTypeTo

}MCVendorType;

@interface MCCallVendorsController ()<UITableViewDataSource,UITableViewDelegate,MCCallVendorTaskCellProtocol , MCCallVendorVendorCellProtocol,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (nonatomic, strong) NSMutableArray *fromModelArray;

@property (nonatomic, strong) NSMutableArray *toModelArray;

@property (nonatomic, strong) NSArray *modelArray;

@property (nonatomic, assign) MCVendorType vendorType;

@property (weak, nonatomic) IBOutlet UITableView *taskVendorsTableView;

@end

@implementation MCCallVendorsController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    [self.activityIndicator startAnimating];

    self.navigationController.navigationBarHidden = YES;

    self.vendorType = MCVendorTypeFrom;

    [self loadModels];

    UIColor *color = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];

    self.searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

    

    

    CGFloat r1 = CGRectGetHeight(self.viewForSwitch.bounds) / 2.0;

    self.viewForSwitch.layer.cornerRadius = r1;

    

    ZJSwitch *switchMoveFromTo = [[ZJSwitch alloc] initWithFrame:CGRectMake(2, 2, self.viewForSwitch.frame.size.width4, self.viewForSwitch.frame.size.height4)];

    switchMoveFromTo.on = NO;

    switchMoveFromTo.backgroundColor = [UIColor clearColor];

    switchMoveFromTo.onTintColor = [UIColor colorWithRed:37/255.0 green:81/255.0 blue:92/255.0 alpha:1];

    switchMoveFromTo.offTintColor = [UIColor colorWithRed:37/255.0 green:81/255.0 blue:92/255.0 alpha:1];

    switchMoveFromTo.textColor = [UIColor blackColor];

    switchMoveFromTo.onText = @”Moving To”;

    switchMoveFromTo.offText = @”Moving From”;

    //switch2.textFont = @””;

    [switchMoveFromTo setOnTextFontSize:7];

    [switchMoveFromTo setOffTextFontSize:7];

    [switchMoveFromTo addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitch addSubview:switchMoveFromTo];

    

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    

    //sample data

    

    // Dispose of any resources that can be recreated.

}

– (void)loadModels

{

    

    NSDictionary *dictionary = @{

                                 @”moveTo”: @”11111″,

                                 @”moveFrom”:@”22222″

                                 };

    

//    [[MCNetworkManager sharedNetworkManager] getVendorsList:dictionary withCompletionBlock:^(NSDictionary *response, NSError *error) {

//        NSLog(@”Response”);

//        NSArray *moveFromArray = response[@”result”][@”move_from”][@”tasks”];

//        NSArray *moveToArray = response[@”result”][@”move_to”][@”tasks”];

//        self.fromModelArray = [NSMutableArray array];

//        self.toModelArray = [NSMutableArray array];

//        [self generateVendorsModelsForArray:moveFromArray moveIntoArray:self.fromModelArray];

//        [self generateVendorsModelsForArray:moveToArray moveIntoArray:self.toModelArray];

//        self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

//        [self.taskVendorsTableView reloadData];

//        [self.activityIndicator stopAnimating];

//        self.activityIndicator.hidden = YES;

//    }];

    

    

    

    self.arrayJson = [Utility parseStatesResponseFileName:@”Json_File” FileType:@”json”];

    NSLog(@”%@”,self.arrayJson);

    

    NSDictionary *response = (NSDictionary *)self.arrayJson;

    

    NSArray *moveFromArray = response[@”result”][@”move_from”][@”tasks”];

            NSArray *moveToArray = response[@”result”][@”move_to”][@”tasks”];

            self.fromModelArray = [NSMutableArray array];

            self.toModelArray = [NSMutableArray array];

            [self generateVendorsModelsForArray:moveFromArray moveIntoArray:self.fromModelArray];

            [self generateVendorsModelsForArray:moveToArray moveIntoArray:self.toModelArray];

            self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

            [self.taskVendorsTableView reloadData];

            [self.activityIndicator stopAnimating];

            self.activityIndicator.hidden = YES;

}

     

     

– (void)generateVendorsModelsForArray:(NSArray *)array moveIntoArray:(NSMutableArray *)movingArray

{

         for(NSDictionary *taskWithVedorsList in array)

         {

             MCCallVendorTaskModel *model = [[MCCallVendorTaskModel alloc] init];

             //set task and vendors list details

             [model setDataFromDictionary:taskWithVedorsList];

             model.expanded = NO;

             [movingArray addObject:model];

         }

}

– (IBAction)switchStateChanged:(id)sender

{

    UISwitch *toFromswitch = (UISwitch *)sender;

    self.vendorType  = (toFromswitch.isOn) ? MCVendorTypeFrom : MCVendorTypeTo;

    [self filterTasks:self.searchTextField.text];

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    MCCallVendorTaskModel *taskModel = self.modelArray[section];

    NSInteger rows = (taskModel.expanded) ? ((taskModel.vendorsArray.count > 5) ? 6 : taskModel.vendorsArray.count) : 0;

    return rows;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *identifier = vendorCell;

    MCCallVendorTaskModel *model = self.modelArray[indexPath.section];

    NSArray *vendorsArray = model.vendorsArray;

    if(indexPath.row > 4 && vendorsArray.count > 5)

    {

        identifier = viewMore;

    }

    MCCallVendorVendorCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    cell.delegate = self;

    cell.section = indexPath.section;

    cell.model = vendorsArray[indexPath.row];

    

    if([identifier isEqualToString:vendorCell])

    {

        //check if last cell and vendor cell

        if((indexPath.row == vendorsArray.count1))

        {

            dispatch_async(dispatch_get_main_queue(), ^{

                UIBezierPath *maskPath;

                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                                 byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                       cornerRadii:CGSizeMake(5.0, 5.0)];

                

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

                maskLayer.path = maskPath.CGPath;

                maskLayer.frame = cell.bounds;

                cell.layer.mask = maskLayer;

                cell.separator.hidden = YES;

            });

        }

        else

        {

            dispatch_async(dispatch_get_main_queue(), ^{

                UIBezierPath *maskPath;

                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                                 byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                       cornerRadii:CGSizeMake(0.0, 0.0)];

                

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

                maskLayer.path = maskPath.CGPath;

                maskLayer.frame = cell.bounds;

                cell.layer.mask = maskLayer;

                if((indexPath.row > 3 && vendorsArray.count > 5))

                {

                    cell.separator.hidden = YES;

                }

                else

                {

                    cell.separator.hidden = NO;

                }

            });

        }

       

    }

    else if ([identifier isEqualToString:viewMore])

    {

        dispatch_async(dispatch_get_main_queue(), ^{

            UIBezierPath *maskPath;

            maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                             byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                   cornerRadii:CGSizeMake(5.0, 5.0)];

            

            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

            maskLayer.path = maskPath.CGPath;

            maskLayer.frame = cell.bounds;

            cell.layer.mask = maskLayer;

        });

    }

    

    return cell;

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return self.modelArray.count;

}

– (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{

    MCCallVendorTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:taskSectionCell];

    cell.delegate = self;

    cell.model = self.modelArray[section];

    dispatch_async(dispatch_get_main_queue(), ^{

        UIBezierPath *maskPath;

        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                         byRoundingCorners:(UIRectCornerTopRight|UIRectCornerTopLeft)

                                               cornerRadii:CGSizeMake(5.0, 5.0)];

        

        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

        maskLayer.path = maskPath.CGPath;

        maskLayer.frame = cell.bounds;

        cell.layer.mask = maskLayer;

    });

    return cell;

}

– (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section

{

    return 20.0;

}

– (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section

{

    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];

    view.backgroundColor = [UIColor clearColor];

    return  view;

}

#pragma mark – Task cell delegates –

– (void)expandCell:(MCCallVendorTaskCell *)cell

{

    for(int i=0; i< self.modelArray.count ; i++)

    {

        MCCallVendorTaskModel *model = self.modelArray[i];

        if(model != cell.model)

        {

            model.expanded = NO;

        }

    }

    cell.model.expanded = !(cell.model.expanded);

    [self.taskVendorsTableView reloadData];

}

#pragma  mark – Vendor cell delegates –

– (void)tappedViewMore:(MCCallVendorVendorCell *)cell

{

    //push a new controller

    MCVendorsListController *vendorsListController = [[UIStoryboard storyboardWithName:vendorsListControllerName bundle:nil] instantiateInitialViewController];

    //pass the selected vendors list,this a a parcular vendor cell, but we need to get list of the vendors for that section

    vendorsListController.model = self.modelArray[cell.section];

    [self.navigationController pushViewController:vendorsListController animated:YES];

}

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell

{

    //call the vendor

    [Utility makeCall:cell.model.vendorPhone];

}

– (IBAction)searchTasks:(id)sender

{

    NSString *textToSearch = ((UITextField *)sender).text ;

    [self filterTasks:textToSearch];

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [self.view endEditing:YES];

    return YES;

}

– (void)filterTasks:(NSString *)filterText

{

    NSLog(@”%@”,filterText);

    if(filterText.length)

    {

        NSArray *taskVendorArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

        NSString* filter =  filterTaskConstant;

        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, @”taskName”,filterText];

        NSArray* filteredData = [taskVendorArray filteredArrayUsingPredicate:predicate];

        //filtered Data

        self.modelArray = filteredData;

        NSLog(@”Filtered Data”);

        [self.taskVendorsTableView reloadData];

    }

    else

    {

        self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

        [self.taskVendorsTableView reloadData];

    }

}

– (IBAction)tapGesture:(id)sender

{

    [self.view endEditing:YES];

}

@end

MCCallVendorTaskCell.h

#import <UIKit/UIKit.h>

#import “MCCallVendorTaskModel.h”

@class MCCallVendorTaskCell;

@protocol MCCallVendorTaskCellProtocol <NSObject>

– (void)expandCell:(MCCallVendorTaskCell *)cell;

@end

@interface MCCallVendorTaskCell : UITableViewCell

@property (nonatomic, strong) MCCallVendorTaskModel *model;

@property (nonatomic, assign) id <MCCallVendorTaskCellProtocol> delegate;

@end

MCCallVendorTaskCell.m

#import “MCCallVendorTaskCell.h”

@interface MCCallVendorTaskCell()

@property (weak, nonatomic) IBOutlet UILabel *taskName;

@property (weak, nonatomic) IBOutlet UIButton *expandButton;

@end

@implementation MCCallVendorTaskCell

– (IBAction)expandButtonAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(expandCell:)])

    {

        [self.delegate expandCell:self];

        [self updateButtonState];

    }

}

– (void)setModel:(MCCallVendorTaskModel *)model

{

    _model = model;

    self.taskName.text = _model.taskName;

    [self updateButtonState];

}

– (void)updateButtonState

{

    if(self.model.expanded)

    {

        [self.expandButton setBackgroundImage:[UIImage imageNamed:@”drop-up”] forState:UIControlStateNormal];

    }

    else

    {

        [self.expandButton setBackgroundImage:[UIImage imageNamed:@”drop-down”] forState:UIControlStateNormal];

    }

}

@end

MCCallVendorTaskModel.h

#import <Foundation/Foundation.h>

#import “MCCallVendorVendorModel.h”

@interface MCCallVendorTaskModel : NSObject

@property (nonatomic, assign) BOOL expanded;

@property (nonatomic, strong) NSString *taskName;

@property (nonatomic, strong) NSMutableArray *vendorsArray; // of type vendors model

– (void)setDataFromDictionary:(NSDictionary *)dictionary;

@end

MCCallVendorTaskModel.m

#import “MCCallVendorTaskModel.h”

@implementation MCCallVendorTaskModel

– (void)setDataFromDictionary:(NSDictionary *)dictionary

{

    self.taskName = dictionary[@”name”];

    //vendors

    self.vendorsArray = [NSMutableArray array];

    NSArray *vendorsArray = dictionary[@”vendors”];

    for(NSDictionary *vendorDictionay in vendorsArray )

    {

        MCCallVendorVendorModel *vendorModel = [[MCCallVendorVendorModel alloc] init];

        [vendorModel setDataFromDictionary:vendorDictionay];

        [self.vendorsArray addObject:vendorModel];

    }

}

@end

MCCallVendorVendorCell.h

#import <UIKit/UIKit.h>

#import “MCCallVendorVendorModel.h”

@class MCCallVendorVendorCell;

@protocol MCCallVendorVendorCellProtocol <NSObject>

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell;

@optional

– (void)tappedViewMore:(MCCallVendorVendorCell *)cell;

@end

@interface MCCallVendorVendorCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIView *separator;

@property (nonatomic, weak) id <MCCallVendorVendorCellProtocol> delegate;

@property (nonatomic, strong) MCCallVendorVendorModel *model;

@property (nonatomic, assign) NSUInteger section;

@end

MCCallVendorVendorCell.m

#import “MCCallVendorVendorCell.h”

@interface MCCallVendorVendorCell ()

@property (weak, nonatomic) IBOutlet UILabel *vendorName;

@end

@implementation MCCallVendorVendorCell

– (void)setModel:(MCCallVendorVendorModel *)model

{

    _model = model;

    self.vendorName.text = _model.vendorName;

}

– (IBAction)callVendorAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(tappedCallVendor:)])

    {

        [self.delegate tappedCallVendor:self];

    }

}

– (IBAction)viewMoreAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(tappedViewMore:)])

    {

        [self.delegate tappedViewMore:self];

    }

}

@end

MCCallVendorVendorModel.h

#import <Foundation/Foundation.h>

@interface MCCallVendorVendorModel : NSObject

@property (nonatomic, strong) NSString *vendorName;

@property (nonatomic, strong) NSString *vendorPhone;

– (void)setDataFromDictionary:(NSDictionary *)dictionary;

@end

#import “MCCallVendorVendorModel.h”

@implementation MCCallVendorVendorModel

– (void)setDataFromDictionary:(NSDictionary *)dictionary

{

    self.vendorName = dictionary[@”name”];

    self.vendorPhone = dictionary[@”phone”];

}

@end

MCVendorsListController.h

#import <UIKit/UIKit.h>

#import “MCCallVendorTaskModel.h”

@interface MCVendorsListController : UIViewController

@property (nonatomic, strong) MCCallVendorTaskModel *model; // task model with name and list of vendors

@end

MCVendorsListController.m

#import “MCVendorsListController.h”

#import “MCCallVendorVendorCell.h”

#import “Utility.h”

NSString *const vendorsFilterString =  @”%K CONTAINS[c] %@”;

NSString *const vendorCellIdentifier = @”vendorCell”;

@interface MCVendorsListController()<UITableViewDataSource, UITableViewDelegate , MCCallVendorVendorCellProtocol>

@property (weak, nonatomic) IBOutlet UITableView *vendorsTableView;

@property (nonatomic, strong) NSArray *modelsArray;

@end

@implementation MCVendorsListController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.navigationController.navigationBarHidden = YES;

    [self loadAllVendors];

}

– (void)loadAllVendors

{

    self.modelsArray = self.model.vendorsArray;

    [self.vendorsTableView reloadData];

}

– (IBAction)backButtonAction:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.modelsArray.count;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    MCCallVendorVendorCell *cell = [tableView dequeueReusableCellWithIdentifier:vendorCellIdentifier];

    cell.model = self.modelsArray[indexPath.row];

    cell.delegate = self;

    return cell;

}

– (IBAction)searchVendors:(id)sender

{

    NSString *textToSearch = ((UITextField *)sender).text ;

    NSLog(@”%@”,textToSearch);

    if(textToSearch.length)

    {

        NSArray *taskVendorArray = self.model.vendorsArray;

        NSString* filter = vendorsFilterString;

        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, @”vendorName”,textToSearch];

        NSArray* filteredData = [taskVendorArray filteredArrayUsingPredicate:predicate];

        //filtered Data

        self.modelsArray = filteredData;

        NSLog(@”Filtered Data”);

        [self.vendorsTableView reloadData];

    }

    else

    {

        self.modelsArray = self.model.vendorsArray;

        [self.vendorsTableView reloadData];

    }

}

#pragma mark – vendor cell delegates –

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell

{

    [Utility makeCall:cell.model.vendorPhone];

}

@end

Download Sample Project From Github

Custom TableView With Searchbar

FPOrderDetailsClass.h

#import <Foundation/Foundation.h>

@interface FPOrderDetailsClass : NSObject

@property(strong,nonatomic)NSString *orders;

@property(strong,nonatomic)NSString *firstname;

@property(strong,nonatomic)NSString *lastname;

@property(strong,nonatomic)NSString *orderdate;

@property(strong,nonatomic)NSString *city;

@property(strong,nonatomic)NSString *state;

@property(strong,nonatomic)NSString *price;

@property(strong,nonatomic)NSArray *productsList;

@end

FPOrderDetailsClass.m

#import “FPOrderDetailsClass.h”

@implementation FPOrderDetailsClass

@end

FPSearchCustomOrdersViewController.h

#import <UIKit/UIKit.h>

@interface FPSearchCustomOrdersViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate>

@property (strong, nonatomic) IBOutlet UITableView *myTableView;

– (IBAction)HomeScreenBackBtn:(id)sender;

@end

FPSearchCustomOrdersViewController.m

#import “FPSearchCustomOrdersViewController.h”

#import “FPOrderDetailsClass.h”

#import “FPSearchCustomerOrderTableViewCell.h”

#import “FPSearchCustomerDetailViewController.h”

@interface FPSearchCustomOrdersViewController ()

{

    NSArray *searchResults;

    NSArray *allArrays;

}

@end

@implementation FPSearchCustomOrdersViewController

@synthesize myTableView;

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    float width;

    float height;

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    FPOrderDetailsClass *custom1=[FPOrderDetailsClass new];

    custom1.orders=@”1″;

    custom1.firstname=@”Daniel”;

    custom1.lastname=@”Anthony”;

    custom1.orderdate=@”1/1/2016″;

    custom1.price=@”$19.90″;

    custom1.city=@”Dallas”;

    custom1.state=@”TX”;

    NSDictionary *dic1 = [[NSDictionary alloc]initWithObjectsAndKeys:@”Productimage1.png”,@”image”,@”SurgeShield Only”,@”name”,@”$9.95 plus tax”,@”detail”,nil];

    NSDictionary *dic2 = [[NSDictionary alloc]initWithObjectsAndKeys:@”Productimage2.png”,@”image”,@”Electronics Surge Protection Only”,@”name”,@”$9.95 plus tax” ,@”detail”,nil];

    NSArray *arr = [[NSArray alloc]initWithObjects:dic1,dic2, nil];

    custom1.productsList = arr;

    NSLog(@”%@”,custom1.productsList);

    FPOrderDetailsClass *custom2=[FPOrderDetailsClass new];

    custom2.orders=@”2″;

    custom2.firstname=@”James”;

    custom2.lastname=@”William”;

    custom2.orderdate=@”3/2/2016″;

    custom2.price=@”$19.90″;

    custom2.city=@”Columbus”;

    custom2.state=@”OH”;

    custom2.productsList=arr;

    FPOrderDetailsClass *custom3=[FPOrderDetailsClass new];

    custom3.orders=@”3″;

    custom3.firstname=@”David”;

    custom3.lastname=@”Andrew”;

    custom3.orderdate=@”5/3/2016″;

    custom3.price=@”$19.90″;

    custom3.city=@”New york”;

    custom3.state=@”NY”;

    custom3.productsList=arr;

    FPOrderDetailsClass *custom4=[FPOrderDetailsClass new];

    custom4.orders=@”4″;

    custom4.firstname=@”Jacob”;

    custom4.lastname=@”kevin”;

    custom4.orderdate=@”7/4/2016″;

    custom4.price=@”$19.90″;

    custom4.city=@”Hampton”;

    custom4.state=@”VA”;

    custom4.productsList=arr;

    FPOrderDetailsClass *custom5=[FPOrderDetailsClass new];

    custom5.orders=@”5″;

    custom5.firstname=@”Gabriel”;

    custom5.lastname=@”John”;

    custom5.orderdate=@”7/4/2016″;

    custom5.price=@”$19.90″;

    custom5.city=@”Miami”;

    custom5.state=@”FL”;

    custom5.productsList=arr;

    allArrays=[NSArray arrayWithObjects:custom1,custom2,custom3,custom4,custom5,nil];

    myTableView.delegate=self;

    [myTableView reloadData];

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        return [searchResults count];

    } else {

        return [allArrays count];

    }

}

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @”Cell”;

    FPSearchCustomerOrderTableViewCell *cell = (FPSearchCustomerOrderTableViewCell*)[self.myTableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)

    {

        cell = [[FPSearchCustomerOrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    FPOrderDetailsClass *customcell= [FPOrderDetailsClass new];

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        customcell=[searchResults objectAtIndex:indexPath.row];

    }

    else

    {

        customcell=[allArrays objectAtIndex:indexPath.row];

    }

    cell.OrdersLbl.text=customcell.orders;

    cell.FtrstName.text=customcell.firstname;

    cell.LastName.text=customcell.lastname;

    cell.DateLbl.text=customcell.orderdate;

    cell.CityLbl.text=customcell.city;

    cell.StateLbl.text=customcell.state;

    cell.PriceLbl.text=customcell.price;

    cell.selectionStyle=UITableViewCellSeparatorStyleNone;

    cell.selectionStyle=UITableViewCellSeparatorStyleNone;

    return cell;

}

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        //        [self performSegueWithIdentifier: @”FPSearchOrderDetailViewController” sender: self];

    }

}

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@”cellToDetailViewController”]) {

        FPSearchCustomerDetailViewController *destViewController = segue.destinationViewController;

        NSIndexPath *indexPath = nil;

        if ([self.searchDisplayController isActive]) {

            indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];

            destViewController.detaillist = [searchResults objectAtIndex:indexPath.row];

        } else {

            indexPath = [myTableView indexPathForSelectedRow];

            destViewController.detaillist = [allArrays objectAtIndex:indexPath.row];

        }

    }

}

– (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope

{

    NSPredicate *namepredicate = [NSPredicate predicateWithFormat:@”firstname contains[c] %@”, searchText];

    NSPredicate *ordernumberpredicate = [NSPredicate predicateWithFormat:@”orders contains[c] %@”, searchText];

    NSPredicate *orderdatepredicate = [NSPredicate predicateWithFormat:@”orderdate contains[c] %@”, searchText];

    NSPredicate *finalpredicate=[NSCompoundPredicate orPredicateWithSubpredicates:@[namepredicate,orderdatepredicate,ordernumberpredicate]];

    searchResults = [allArrays filteredArrayUsingPredicate:finalpredicate];

}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{

    [self filterContentForSearchText:searchString

                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]

                                      objectAtIndex:[self.searchDisplayController.searchBar

                                                     selectedScopeButtonIndex]]];

    return YES;

}

– (IBAction)HomeScreenBackBtn:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

@end

FPSearchCustomerDetailOrderTableViewCell.h

#import <UIKit/UIKit.h>

@interface FPSearchCustomerDetailOrderTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UIImageView *ProductImage;

@property (strong, nonatomic) IBOutlet UILabel *ProductNameLbl;

@property (strong, nonatomic) IBOutlet UILabel *ProductCostLbl;

@end

FPSearchCustomerDetailOrderTableViewCell.m

#import “FPSearchCustomerDetailOrderTableViewCell.h”

@implementation FPSearchCustomerDetailOrderTableViewCell

– (void)awakeFromNib {

    // Initialization code

}

– (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

}

@end

FPSearchCustomerDetailViewController.h

#import <UIKit/UIKit.h>

#import “FPOrderDetailsClass.h”

@interface FPSearchCustomerDetailViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UILabel *OrderLbl;

@property(strong,nonatomic)FPOrderDetailsClass *detaillist;

@property (strong, nonatomic) IBOutlet UIButton *SearchOrdersBackBtn;

@property (weak, nonatomic) IBOutlet UITableView *tblSearchCustomDetail;

– (IBAction)SearchOrdersBackBtn:(id)sender;

@end

FPSearchCustomerDetailViewController.m

#import “FPSearchCustomerDetailViewController.h”

#import “FPSearchCustomerDetailOrderTableViewCell.h”

@interface FPSearchCustomerDetailViewController ()

{

    NSMutableArray *productslistArray;

    NSMutableArray *productsImagesArray;

    NSMutableArray *productsCostArray;

}

@end

@implementation FPSearchCustomerDetailViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.OrderLbl.text=[self.detaillist valueForKey:@”orders”];

    float width;

    float height;

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    self.tblSearchCustomDetail.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.detaillist.productsList count];

}

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    FPSearchCustomerDetailOrderTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@”Cell”];

    if (cell==nil) {

        cell=[[FPSearchCustomerDetailOrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”Cell”];

    }

    cell.ProductNameLbl.text=[[self.detaillist.productsList objectAtIndex:indexPath.row]objectForKey:@”name”];

    cell.ProductImage.image=[UIImage imageNamed:[[self.detaillist.productsList objectAtIndex:indexPath.row]objectForKey:@”image”]];

    cell.ProductCostLbl.text=[[self.detaillist.productsList objectAtIndex:indexPath.row]objectForKey:@”detail”];

    cell.selectionStyle=UITableViewCellSelectionStyleNone;

    cell.selectionStyle=UITableViewCellSeparatorStyleNone;

    return cell;

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

// Get the new view controller using [segue destinationViewController].

// Pass the selected object to the new view controller.

}

*/

– (IBAction)SearchOrdersBackBtn:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

@end

FPSearchCustomerOrderTableViewCell.h

#import <UIKit/UIKit.h>

@interface FPSearchCustomerOrderTableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *OrdersLbl;

@property (weak, nonatomic) IBOutlet UILabel *DateLbl;

@property (weak, nonatomic) IBOutlet UILabel *FtrstName;

@property (weak, nonatomic) IBOutlet UILabel *LastName;

@property (weak, nonatomic) IBOutlet UILabel *CityLbl;

@property (weak, nonatomic) IBOutlet UILabel *StateLbl;

@property (weak, nonatomic) IBOutlet UILabel *PriceLbl;

@end

FPSearchCustomerOrderTableViewCell.m

#import “FPSearchCustomerOrderTableViewCell.h”

@implementation FPSearchCustomerOrderTableViewCell

– (void)awakeFromNib {

    // Initialization code

}

– (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

}

@end

Download Sample Project From Github

Hit Api with AFNetworking Library

ViewController.h

#import <UIKit/UIKit.h>

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@interface ViewController : UIViewController

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

– (IBAction)btnLoadImage:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

@end

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

ImageCache.h

#import <Foundation/Foundation.h>

@interface ImageCache : NSObject

+ (void) resetCache;

+ (void) setObject:(NSData*)data forKey:(NSString*)key;

+ (id) objectForKey:(NSString*)key;

@end

ImageCache.m

#import “ImageCache.h”

static NSTimeInterval cacheTime =  (double)604800;

@implementation ImageCache

+ (void) resetCache

{

    [[NSFileManager defaultManager] removeItemAtPath:[ImageCache cacheDirectory] error:nil];

}

+ (NSString*) cacheDirectory

{

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString *cacheDirectory = [paths objectAtIndex:0];

    cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@”ImageCaches”];

    return cacheDirectory;

}

+ (NSData*) objectForKey:(NSString*)key

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

    if ([fileManager fileExistsAtPath:filename])

    {

        NSDate *modificationDate = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];

        if ([modificationDate timeIntervalSinceNow] > cacheTime) {

            [fileManager removeItemAtPath:filename error:nil];

        } else {

            NSData *data = [NSData dataWithContentsOfFile:filename];

            return data;

        }

    }

    return nil;

}

+ (void) setObject:(NSData*)data forKey:(NSString*)key

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

    BOOL isDir = YES;

    if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir])

    {

        [fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];

    }

    NSError *error;

    @try {

        [data writeToFile:filename options:NSDataWritingAtomic error:&error];

    }

    @catch (NSException * e) {

        //TODO: error handling maybe

        NSLog(@”Data not saved”);

    }

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

Download Sample Project From Github

Image Cache with Imagecache Library

ViewController.h

#import <UIKit/UIKit.h>

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@interface ViewController : UIViewController

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

– (IBAction)btnLoadImage:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

@end

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

ImageCache.h

#import <Foundation/Foundation.h>

@interface ImageCache : NSObject

+ (void) resetCache;

+ (void) setObject:(NSData*)data forKey:(NSString*)key;

+ (id) objectForKey:(NSString*)key;

@end

ImageCache.m

#import “ImageCache.h”

static NSTimeInterval cacheTime =  (double)604800;

@implementation ImageCache

+ (void) resetCache

{

    [[NSFileManager defaultManager] removeItemAtPath:[ImageCache cacheDirectory] error:nil];

}

+ (NSString*) cacheDirectory

{

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString *cacheDirectory = [paths objectAtIndex:0];

    cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@”ImageCaches”];

    return cacheDirectory;

}

+ (NSData*) objectForKey:(NSString*)key

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

    if ([fileManager fileExistsAtPath:filename])

    {

        NSDate *modificationDate = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];

        if ([modificationDate timeIntervalSinceNow] > cacheTime) {

            [fileManager removeItemAtPath:filename error:nil];

        } else {

            NSData *data = [NSData dataWithContentsOfFile:filename];

            return data;

        }

    }

    return nil;

}

+ (void) setObject:(NSData*)data forKey:(NSString*)key

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

    BOOL isDir = YES;

    if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir])

    {

        [fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];

    }

    NSError *error;

    @try {

        [data writeToFile:filename options:NSDataWritingAtomic error:&error];

    }

    @catch (NSException * e) {

        //TODO: error handling maybe

        NSLog(@”Data not saved”);

    }

}

@end

Download Sample Project From Github

Custom CollectionView

ViewController.h

#import <UIKit/UIKit.h>

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@interface ViewController : UIViewController

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

– (IBAction)btnLoadImage:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

@end

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Download Sample Project From Github

Xib Cell Use in CollectionView

<UICollectionViewDataSource,UICollectionViewDelegate>

VendorListViewController.m

#import “VendorListViewController.h”

#import “NibCell.h”

@interface VendorListViewController ()

@end

@implementation VendorListViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    self.navigationController.navigationBarHidden=YES;

    UINib *cellNib = [UINib nibWithNibName:@”NibCell” bundle:nil];

    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@”cvCell”];

    

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(150, 200)];

    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

    [self.collectionView setCollectionViewLayout:flowLayout];

    

    

    // Do any additional setup after loading the view from its nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return 11;

}

-(NibCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    

    static NSString *cellIdentifier = @”cvCell”;

    NibCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    NSLog(@”%ld”,(long)indexPath.row);

    cell.btniblt.tag = (long)indexPath.row;

    return cell;

    

}

#pragma mark collection view cell paddings

– (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    return UIEdgeInsetsMake(0, 20, 10, 20); // top, left, bottom, right

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”%ld”,(long)indexPath.row);

    

}

@end

NibCell.h

#import <UIKit/UIKit.h>

@interface NibCell : UICollectionViewCell

@property (strong, nonatomic) IBOutlet UIButton *btniblt;

– (IBAction)pressButton:(id)sender;

@end

NibCell.m

#import “NibCell.h”

@implementation NibCell

– (void)awakeFromNib {

    // Initialization code

}

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

    }

    return self;

}

– (IBAction)pressButton:(id)sender {

    

    NSLog(@”%@”,sender);

    

        NSString *str = [NSString stringWithFormat:@”Button Clicked :: %ld”,(long)_btniblt.tag];

    

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@””

                                                        message:str

                                                       delegate:nil

                                              cancelButtonTitle:@”OK”

                                              otherButtonTitles:nil];

        [alert show];

    NSLog(@”%ld”,(long)_btniblt.tag);

}

@end

Download Sample Project From Github

When use UITapGestureRecognizer in UITableView didSelectRowAtIndexPath Not working

<UIGestureRecognizerDelegate>

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapGestureRecognizer:)];

    tapGesture.delegate = self;

    [self.view addGestureRecognizer:tapGesture];

#pragma mark UIGestureRecognizerDelegate methods

– (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

{

    if ([touch.view isDescendantOfView:_tableView]) {

        

        // Don’t let selections of auto-complete entries fire the

        // gesture recognizer

        return NO;

    }

    

    return YES;

}

Update Multiplier with NSLayoutConstraint+Multiplier

ViewController.h

#import <UIKit/UIKit.h>

#import “NSLayoutConstraint+Multiplier.h”

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutConstraintViewHeight;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

//    _layoutConstraintViewHeight.constant = 100;

    

    self.layoutConstraintViewHeight = [self.layoutConstraintViewHeight updateMultiplier:0.5];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

NSLayoutConstraint+Multiplier.h

#import <UIKit/UIKit.h>

@interface NSLayoutConstraint (Multiplier)

-(instancetype)updateMultiplier:(CGFloat)multiplier;

@end

NSLayoutConstraint+Multiplier.m

#import “NSLayoutConstraint+Multiplier.h”

@implementation NSLayoutConstraint (Multiplier)

-(instancetype)updateMultiplier:(CGFloat)multiplier {

    NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:self.firstItem attribute:self.firstAttribute relatedBy:self.relation toItem:self.secondItem attribute:self.secondAttribute multiplier:multiplier constant:self.constant];

    [newConstraint setPriority:self.priority];

    newConstraint.shouldBeArchived = self.shouldBeArchived;

    newConstraint.identifier = self.identifier;

    newConstraint.active = true;

    

    [NSLayoutConstraint deactivateConstraints:[NSArray arrayWithObjects:self, nil]];

    [NSLayoutConstraint activateConstraints:[NSArray arrayWithObjects:newConstraint, nil]];

    //NSLayoutConstraint.activateConstraints([newConstraint])

    return newConstraint;

}

@end

Download Sample Project From Github

Custom UIView XIB Add On UIViewController

ViewController.h

#import <UIKit/UIKit.h>

#import “EPPZDecoupledView.h”

@interface ViewController : UIViewController<EPPZDecoupledViewDelegate>

-(IBAction)showDecoupledView;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    /*

    // Instantiate the nib content without any reference to it.

    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@”View” owner:nil options:nil];

    // Find the view among nib contents (not too hard assuming there is only one view in it).

    UIView *plainView = [nibContents lastObject];

    // Some hardcoded layout.

//    CGSize padding = (CGSize){ 220.0, 220.0 };

//    plainView.frame = (CGRect){padding.width, padding.height, plainView.frame.size};

    plainView.frame = CGRectMake(0, 0, 100, 100);

    // Add to the view hierarchy (thus retain).

    [self.view addSubview:plainView];

    

//    plainView.hidden = YES;

    */

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

-(IBAction)showDecoupledView

{

    [EPPZDecoupledView presentInViewController:self];

}

-(void)decoupledViewTouchedUp:(EPPZDecoupledView*) decoupledView

{ /* Whatever feature. */ }

-(void)decoupledViewDidDismiss:(EPPZDecoupledView*) decoupledView

{ /* Acknowledge sadly. */ }

@end

EPPZDecoupledView.h

#import <UIKit/UIKit.h>

@class EPPZDecoupledView;

@protocol EPPZDecoupledViewDelegate

-(void)decoupledViewTouchedUp:(EPPZDecoupledView*) decoupledView;

-(void)decoupledViewDidDismiss:(EPPZDecoupledView*) decoupledView;

@end

@interface EPPZDecoupledView : UIView

// Indicate that this view should be presented only controllers those implements the delegate methods.

+(void)presentInViewController:(UIViewController<EPPZDecoupledViewDelegate>*) viewController;

-(IBAction)viewTouchedUp;

-(IBAction)dismiss;

@end

EPPZDecoupledView.m

#import “EPPZDecoupledView.h”

@interface EPPZDecoupledViewOwner : NSObject

@property (nonatomic, weak) IBOutlet EPPZDecoupledView *decoupledView;

@end

@implementation EPPZDecoupledViewOwner

@end

@interface EPPZDecoupledView ()

@property (nonatomic, weak) UIViewController <EPPZDecoupledViewDelegate> *delegateViewController;

@end

@implementation EPPZDecoupledView

+(void)presentInViewController:(UIViewController<EPPZDecoupledViewDelegate>*) viewController

{

    // Instantiating encapsulated here.

    EPPZDecoupledViewOwner *owner = [EPPZDecoupledViewOwner new];

    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:owner options:nil];

    

    // Pass in a reference of the viewController.

    owner.decoupledView.delegateViewController = viewController;

    

    // Add (thus retain).

    [viewController.view addSubview:owner.decoupledView];

}

-(IBAction)viewTouchedUp

{

    // Forward to delegate.

    [self.delegateViewController decoupledViewTouchedUp:self];

}

-(IBAction)dismiss

{

    [self removeFromSuperview];

    

    // Forward to delegate.

    [self.delegateViewController decoupledViewDidDismiss:self];

}

@end

Download Sample Project From Github

View Up Down for keyboard show Hide

<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *textFieldActive;

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self.view addGestureRecognizer:tapGesture];

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    if (_textFieldActive != _textFieldReferalID && _textFieldActive != _textFieldMailingAddress) {

        //    iPhone = -210

        //    iPad = -230

        [self viewUpDownWithAnimationYCoordinate:-230];

    }

    

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

    [self viewUpDownWithAnimationYCoordinate:0];

}

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

{

    // return NO to not change text

    return YES;

    

}

– (BOOL)textFieldShouldClear:(UITextField *)textField

{

    // called when clear button pressed. return NO to ignore (no notifications)

    return NO;

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (void)viewUpDownWithAnimationYCoordinate:(float)yCoordinare

{

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:0.35f];

    CGRect frame = self.view.frame;

    frame.origin.y = yCoordinare;

    [self.view setFrame:frame];

    [UIView commitAnimations];

    

}

#pragma mark –

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [_textFieldActive resignFirstResponder];

    [self.view endEditing:YES];// this will do the trick

    

}

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    

}

View Constraint set Programetically

UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];

    redView.backgroundColor = [UIColor redColor];

    redView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:redView];

    // Width

    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:200]];

    // Height

    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:100]];

    // X

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];

    // Y

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

    [self.view addSubview:redView];

In two Button (Male / Female) Find out if first button selected second button should be unselected if second button selected first button should be unselected

UIButton

two buttons Male and Female

Male button in Storyboard

Inspector area – State Config – Default

Male Button BackGround – Round_UnSelected // Set image

Inspector area – State Config – Selected

Male Button BackGround – Round_Selected // Set image

Female button in Storyboard

Inspector area – State Config – Default

Female Button BackGround – Round_UnSelected // Set image

Inspector area – State Config – Selected

Female Button BackGround – Round_Selected // Set image

– (IBAction)buttonActionMale:(id)sender {

    if (!_buttonMale.selected)

    {

        _buttonMale.selected = !_buttonMale.selected;

    }

    _buttonFemale.selected = NO;

}

– (IBAction)buttonActionFemale:(id)sender {

    if (!_buttonFemale.selected)

    {

        _buttonFemale.selected = !_buttonFemale.selected;

    }

    _buttonMale.selected = NO;

}

– (void)getMaleFemaleSelectedDetail

{

    

    if (self.buttonMale.selected)

    {

        NSLog(@”Male”);

        

    }

    

    else if(self.buttonFemale.selected)

    {

        NSLog(@”Female”);

        

    }

    

}

Coredata Sample Code

ViewController.h

#import <UIKit/UIKit.h>

#import “CoreDataUtility.h”

#import “Form.h”

#import “Utility.h”

@interface ViewController : UIViewController

– (IBAction)buttonActionInsertData:(id)sender;

– (IBAction)buttonActionFetchData:(id)sender;

– (IBAction)buttonActionUpdataData:(id)sender;

– (IBAction)buttonActionDeleteData:(id)sender;

– (IBAction)buttonActionViewAllData:(id)sender;

– (IBAction)buttonActionDeleteAllData:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)buttonActionInsertData:(id)sender {

    

    {

    NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                    @”Philippe”, @”firstName”,

                                                    @”Wilson”, @”lastName”,

                                                    @”1212121212″, @”phoneNumber”,

                                                    @”California”, @”city”,

                                                    @”11″, @”rollNo”, nil];

    

    [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    {

        NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                        @”Ales”, @”firstName”,

                                                        @”Wilson”, @”lastName”,

                                                        @”1717171717″, @”phoneNumber”,

                                                        @”USA”, @”city”,

                                                        @”12″, @”rollNo”, nil];

        

        [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    {

        NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                        @”Steave”, @”firstName”,

                                                        @”Reonaldo”, @”lastName”,

                                                        @”123456790″, @”phoneNumber”,

                                                        @”California”, @”city”,

                                                        @”13″, @”rollNo”, nil];

        

        [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    

}

– (IBAction)buttonActionFetchData:(id)sender {

    

    {

   Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”11″];

    

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

    }

    

    {

        Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”12″];

        

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

        

        

    }

    {

        Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”13″];

        

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

    }

}

– (IBAction)buttonActionUpdataData:(id)sender {

    

    

    NSMutableDictionary *dictionaryStudentUpdateDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                          @”NewSteave”, @”firstName”,

                                                          @”NewReonaldo”, @”lastName”,

                                                          @”+91123456790″, @”phoneNumber”,

                                                          @”New York”, @”city”,

                                                          @”13″, @”rollNo”, nil];

    

    

    

    

    [CoreDataUtility updateData:dictionaryStudentUpdateDetail];

}

– (IBAction)buttonActionDeleteData:(id)sender {

    

    [CoreDataUtility deleteStudentDetailRollNo:@”12″];

}

– (IBAction)buttonActionViewAllData:(id)sender {

    

    NSArray *arrayAllData = [[NSArray alloc]initWithArray:[CoreDataUtility getAllRecords]];

    NSLog(@”%@”,arrayAllData);

    

    if (arrayAllData.count > 0)

    {

        for (int i = 0; i<[arrayAllData count]; i++)

        {

           NSLog(@”%@”,[[arrayAllData objectAtIndex:i]valueForKey:@”firstName”]);

        }

        

    }

}

– (IBAction)buttonActionDeleteAllData:(id)sender {

    

    [CoreDataUtility deleteAllRecords];

}

@end

CoreDataManager.h

#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>

@interface CoreDataManager : NSObject

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

+ (CoreDataManager *)sharedCoreDataManager;

– (void)saveContext;

– (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data

@end

CoreDataManager.m

#import “CoreDataManager.h”

@implementation CoreDataManager

@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

+ (CoreDataManager *)sharedCoreDataManager

{

    static CoreDataManager *sharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[CoreDataManager alloc]init];

    });

    return sharedInstance;

}

#pragma mark – Application’s Documents directory

// Returns the URL to the application’s Documents directory.

– (NSURL *)applicationDocumentsDirectory{

    // The directory the application uses to store the Core Data store file. This code uses a directory named “Apple.coreDataApple” in the application’s documents directory.

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

// Returns the managed object model for the application.

// If the model doesn’t already exist, it is created from the application’s model.

– (NSManagedObjectModel *)managedObjectModel

{

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”CoreDataModel” withExtension:@”momd”];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

/*

// Returns the persistent store coordinator for the application.

// If the coordinator doesn’t already exist, it is created and the application’s store added to it.

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

if (_persistentStoreCoordinator != nil) {

return _persistentStoreCoordinator;

}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreDataModel.sqlite”];

NSError *error = nil;

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

//         Replace this implementation with code to handle the error appropriately.

//

//         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

//

//         Typical reasons for an error here include:

//         * The persistent store is not accessible;

//         * The schema for the persistent store is incompatible with current managed object model.

//         Check the error message to determine what the actual problem was.

//

//         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application’s resources directory instead of a writeable directory.

//

//         If you encounter schema incompatibility errors during development, you can reduce their frequency by:

//         * Simply deleting the existing store:

//         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

//

//         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:

//         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

//

//         Lightweight migration will only work for a limited set of schema changes; consult “Core Data Model Versioning and Data Migration Programming Guide” for details.

NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

abort();

}

return _persistentStoreCoordinator;

}

*/

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    

    // Create the coordinator and store

    

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreDataModel.sqlite”];

    NSError *error = nil;

    NSString *failureReason = @”There was an error creating or loading the application’s saved data.”;

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        dict[NSLocalizedDescriptionKey] = @”Failed to initialize the application’s saved data”;

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSError errorWithDomain:@”YOUR_ERROR_DOMAIN” code:9999 userInfo:dict];

        // Replace this with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

        abort();

    }

    

    return _persistentStoreCoordinator;

}

// Returns the managed object context for the application.

// If the context doesn’t already exist, it is created and bound to the persistent store coordinator for the application.

– (NSManagedObjectContext *)managedObjectContext

{

    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (!coordinator)

    {

        return nil;

    }

    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    

    return _managedObjectContext;

}

#pragma mark – Core Data Saving support

– (void)saveContext{

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        NSError *error = nil;

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

            abort();

        }

    }

}

@end

CoreDataUtility.h

#import <Foundation/Foundation.h>

#import “CoreDataManager.h”

#import “Form.h”

@interface CoreDataUtility : NSObject

+ (void)insertData:(id)aData;

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo;

+ (void)updateData:(id)aData;

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo;

+ (NSArray *)getAllRecords;

+ (void)deleteAllRecords;

@end

CoreDataUtility.m

#import “CoreDataUtility.h”

@implementation CoreDataUtility

+ (void)insertData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    

    Form *aForm = (Form *)[NSEntityDescription insertNewObjectForEntityForName:@”Form” inManagedObjectContext:[[CoreDataManager sharedCoreDataManager]managedObjectContext]];

    

    aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

    aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

    aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

    aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

    aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    

    

    NSError *error = nil;

    [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

    

}

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo

{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@”Form” inManagedObjectContext:[[CoreDataManager sharedCoreDataManager]managedObjectContext]];

    [fetchRequest setEntity:entity];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@”rollNo == %@”, aRollNo];

    [fetchRequest setPredicate:predicate];

    

    NSError *error = nil;

    

    NSArray *fetchResults = [[[CoreDataManager sharedCoreDataManager]managedObjectContext] executeFetchRequest:fetchRequest error:&error];

    

    Form *aForm = [fetchResults lastObject];

    return aForm;

    

}

+ (void)updateData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    

    NSString *rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    Form *aForm = [self getStudentDetailRollNo:rollNo];

    

    if (aForm != nil)

    {

        aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

        aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

        aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

        aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

        aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

        

        NSError *error = nil;

        [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

        

    }

    else

    {

        NSLog(@”Record Not Found”);

    }

    

}

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo

{

    

    Form *aForm = [self getStudentDetailRollNo:aRollNo];

    

    if (aForm != nil)

    {

        [[[CoreDataManager sharedCoreDataManager]managedObjectContext] deleteObject:aForm];

    }

    NSError *error = nil;

    [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

}

+ (NSArray *)getAllRecords

{

    

    

    NSManagedObjectContext *context =[[CoreDataManager sharedCoreDataManager]managedObjectContext];

    

    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@”Form”];

    

    NSError *error = nil;

    NSArray *arrayresults = [context executeFetchRequest:request error:&error];

    

    for (NSManagedObject *obj in arrayresults)

    {

        NSArray *keys = [[[obj entity] attributesByName] allKeys];

        NSArray *values = [[[obj entity] attributesByName] allValues];

        

        NSLog(@”%@”,keys);

        NSLog(@”%@”,values);

        

    }

    

    return arrayresults;

}

+ (void)deleteAllRecords;

{

    

    NSPersistentStore *store = [[[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] persistentStores] lastObject];

    NSError *error = nil;

    NSURL *storeURL = store.URL;

    [[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] removePersistentStore:store error:&error];

    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

    

    //Make new persistent store for future saves   (Taken From Above Answer)

    if (![[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

    {

        // do something with the error

        NSLog(@”%@”,error);

    }

    else

    {

        NSLog(@”Data Reset”);

    }

    

}

@end

Download Sample Project From Github

Get Description From Object in Utility Class

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+ (NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”\n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

Convert Dic To String For GET API with NSDictionary+UrlEncoding Category

ViewController.m

#import “NSDictionary+UrlEncoding.h”

NSDictionary *dictionaryNew = @{@”key”: @”28c15c0b405c1f7a107133edf5504367″,

                                    @”name”: @”Rohan Kadam”,

                                    @”mobile_no”: @”9111111111″,

                                    @”email_id”: @”rohank989@gmail.com”,

                                    @”password”: @”1234″,

                                    @”mode”: @”R”,};

    

    NSLog(@”%@”,dictionaryNew);

    NSLog(@”%@”,[dictionaryNew urlEncodedString]);

    

    

    NSString *stringURLForGetResponce = [NSString stringWithFormat:@”%@%@”,@”http://shagunn.info/cherishws/webservices/userRegistration?&#8221;,[dictionaryNew urlEncodedString]];

    NSLog(@”%@”,stringURLForGetResponce);

Download Sample Project From Github

Before Hit API set Secure connection

open Info.plist

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”&gt;

<plist version=”1.0″>

<dict>

<key>NSAllowsArbitraryLoads</key>

<true/>

<key>NSExceptionDomains</key>

<dict>

<key>akamaihd.net</key>

<dict>

<key>NSIncludesSubdomains</key>

<true/>

<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>

<false/>

</dict>

<key>facebook.com</key>

<dict>

<key>NSIncludesSubdomains</key>

<true/>

<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>

<false/>

</dict>

<key>fbcdn.net</key>

<dict>

<key>NSIncludesSubdomains</key>

<true/>

<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>

<false/>

</dict>

</dict>

</dict>

</plist>

Hit API with NSURLSession get response

<NSURLSessionDelegate>

-(void)getJsonResponse : (NSString *)urlStr success : (void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure

{

    

    

    NSURLSession * session = [NSURLSession sharedSession];

    NSURL * url = [NSURL URLWithString: urlStr];

    

    

    // Asynchronously Api is hit here

    NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)

                                       {

                                           

                                           NSLog(@”%@”,data);

                                           

                                           NSDictionary * json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

                                           NSLog(@”%@”,json);

                                           success(json);

                                           

                                           

                                           

                                       }];

    

    [dataTask resume] ; // Executed First

    

    

}

AlertController with textfield

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@”Enter Referance”

                                                                       message:nil

                                                                preferredStyle:UIAlertControllerStyleAlert];

        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            // optionally configure the text field

            textField.keyboardType = UIKeyboardTypeDefault;

        }];

        

        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@”OK”

                                                           style:UIAlertActionStyleDefault

                                                         handler:^(UIAlertAction *action) {

                                                             UITextField *textFieldEnterOtherReferance = [alertController.textFields firstObject];

                                                             NSLog(@”%@”,textFieldEnterOtherReferance.text);

                                                             if ([Utility trimString_RemoveWhiteSpaceFromString:textFieldEnterOtherReferance.text].length != 0)

                                                             {

                                                                 _labelReferance.text = textFieldEnterOtherReferance.text;

                                                             }

                                                             _viewPopUpBelowTable.hidden = YES;

                                                             _tableViewPopUp.hidden = YES;

                                                         }];

        [alertController addAction:okAction];

        [self presentViewController:alertController animated:YES completion:nil];

Hit Api With AFNetworking Library

ViewController.m

#import “ViewController.h”

#import “FTTask.h”

#import “Helper.h”

#import “RequestManager.h”

#import “NetworkConstants.h”

#import “AppConstants.h”

#import “FTAutoSuggestedSearchJsonModel.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)buttonActionClickToHitAPI:(id)sender

{

    

    [self hitAPIsearchString:@”u”];

    

    /*

    [self getTrialDetailsTrialID:40786];

    */

    

    /*

    [self hitlocationcityAPI:@”u”];

    

     */

    

    /*

    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:@[@”email”,@”amit@yopmail.com”,@”123456″] forKeys:@[@”identity”,@”email”,@”password”]];

    

    [self customerLogin:dictionary];

     */

    

}

-(void)customerLogin:(NSDictionary *) params

{

   // if([Helper internetIsOn])

    {

        

        FTTask *login = [[RequestManager sharedInstance] getUserLoginTask:params];

        [login setCompletionhandler:^(NSDictionary *request, id response) {

            

            NSLog(@”%@”,response);

            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

            [defaults setObject:response[@”token”] forKey:@”userToken”];

            

            FTTask *getProfile = [[RequestManager sharedInstance] getUserProfile:@{@”authorization”:response[@”token”]}];

            [getProfile setCompletionhandler:^(NSDictionary *request, id response)

             {

                 NSLog(@”%@”,response[@”customer”]);

                 NSData *userProfileData = [NSKeyedArchiver archivedDataWithRootObject:response[@”customer”]];

                 [defaults setObject:userProfileData forKey:@”userProfile”];

                 

                 

                 

             } error:^(NSDictionary *request, id response) {

                 

                 NSString *errorMessage = response[@”message”];

                 if ([response[ERRORCODE] isEqualToNumber:[NSNumber numberWithInteger:666]])

                 {

                     errorMessage = NETWORK_ERROR_MESSAGE;

                 }

                 

                 [Helper makeAlert:errorMessage  withTitle:ERROR_TEXT];

                 

              

             }];

            

           

            

        } error:^(NSDictionary *request, id response) {

            

            NSLog(@”%@”,response);

                

                NSString *errorMessage = response[@”message”];

                if ([response[ERRORCODE] isEqualToNumber:[NSNumber numberWithInteger:666]]) {

                    errorMessage = NETWORK_ERROR_MESSAGE;

                }

                

                [Helper makeAlert:errorMessage  withTitle:ERROR_TEXT];

            

        }];

    }

//    else

//    {

//        UIAlertView *alert = [Helper makeNetworkAlert];

//        [alert show];

//    }

}

– (void)hitlocationcityAPI:(NSString *)searchString

{

    

    

    NSMutableDictionary *params = [NSMutableDictionary new];

    //        params[@”keyword”] = self.searchString;

    //        FTLocationUserDefaultModel *location = [[FTUserDefaults shared] getUserLocationData];

    //

    //        if((location.latitude != nil && (![location.latitude isEqual:[NSNull null]])) && (location.longitude != nil && ![location.longitude isEqual:[NSNull null]]))

    //        {

    //            params[@”location”] = @{@”city” : location.selectedCity,

    //                                    @”lat”:location.latitude,

    //                                    @”long”:location.longitude

    //                                    };

    //        }

    //        else

    //        {

    //            params[@”location”] = @{@”city” : location.selectedCity};

    //        }

    //

    //        if (isNew == YES)

    //        {

    //            self.currentPage = @0;

    //            self.recordsPerPage = @20;

    //        }

    //

    //        params[@”offset”] = @{@”from” : self.currentPage , @”number_of_records” : [self.recordsPerPage stringValue]};

    

    //        FTLocationUserDefaultModel *location = [[FTUserDefaults shared] getUserLocationData];

    //        NSLog(@”%@”,[location.selectedCity capitalizedString]);

    //        NSLog(@”%@”,[[location.selectedCity capitalizedString] stringByReplacingOccurrencesOfString:@” ” withString:@”-“]);

    //        params[@”city”] = [[location.selectedCity capitalizedString] stringByReplacingOccurrencesOfString:@” ” withString:@”-“];

    

    

    NSString *stringSearchLocation = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

    FTTask *keywordSearchTask = [[RequestManager sharedInstance] createAutoSuggestedSearchLocation:params searchString:stringSearchLocation];

    [keywordSearchTask setCompletionhandler:^(NSDictionary *request, id response)

     {

         

         

         //    self.totalRecords = response.meta.total_records;

         NSLog(@”%@”,response);

                 DebugLog(@”response results==>%lu”, (unsigned long)[[response objectForKey:@”location”] count]);

         

        

         

     }error:^(NSDictionary *request, NSDictionary *response)

     {

         NSLog(@”error in getting rank finder api”);

     }];

}

-(void)getTrialDetailsTrialID:(int)trialId

{

    

//   if([Helper isUserLoggedIn])

    {

        

        FTTask *homeData = [[RequestManager sharedInstance]getTrialDetailsPageDataForTrialId:trialId];

        

        [homeData setCompletionhandler:^(NSDictionary *request, id response) {

            NSLog(@”%@”,response);

            

        }error:^(NSDictionary *request, id response) {

            

             NSLog(@”%@”,response);

        }];

        

    }

    

    

}

– (void)hitAPIsearchString:(NSString *)searchString

{

    NSMutableDictionary *params = [NSMutableDictionary new];

    params[@”keyword”] = searchString;

   

    params[@”location”] = @{@”city” : @”mumbai”};

    

    self.currentPage = 0;

    //self.recordsPerPage = 20;

    

    params[@”offset”] = @{@”from” : @”0″ , @”number_of_records” : @”20″};

    

    FTTask *keywordSearchTask = [[RequestManager sharedInstance] createAutoSuggestedSearchTask:params];

    [keywordSearchTask setCompletionhandler:^(NSDictionary *request, FTAutoSuggestedSearchJsonModel *response)

     {

         

        NSLog(@”%@”,response);

         

        DebugLog(@”response results==>%lu”, (unsigned long)response.results.count);

         

     }error:^(NSDictionary *request, NSDictionary *response)

     {

         NSLog(@”%@”,response);

         NSLog(@”error in getting rank finder api”);

     }];

}

@end

RequestManager.h

#import <Foundation/Foundation.h>

#import “FTTask.h”

@interface RequestManager : NSObject

+ (RequestManager *) sharedInstance;

-(FTTask *)createRankFinderTask:(NSDictionary *)params;

-(FTTask *)createKeywordSearchTask:(NSDictionary *)params;

-(FTTask *) getRegistrationTask:(NSDictionary *) params;

-(FTTask *) getUserLoginTask:(NSDictionary *) params;

-(FTTask *)postNotificationSettings:(NSDictionary *)params optionalParams:(NSDictionary *)aOptionalParams;

-(FTTask *) getHomeScreenData:(NSString *) city;

-(FTTask *)createAutoSuggestedSearchTask:(NSDictionary *)params;

-(FTTask *)createAutoSuggestedSearchLocation:(NSDictionary *)params searchString:(NSString *)asearchString;

-(FTTask *) getFinderResults:(NSDictionary *) params;

-(FTTask *) getSelectedVenderList:(NSString *) param;

-(FTTask *) getTrialsList:(NSString *) param;

-(FTTask *) getCities;

-(FTTask *) getArea :(NSString*)cityName;

– (FTTask*)vendorDetailTask:(NSString*)vendorName;

-(FTTask *) getAllBookmarks:(NSString*)userId;

-(FTTask *) getOffersTabData:(NSString *) city;

-(FTTask *) getRequestCallBackTask:(NSDictionary *) params;

-(FTTask *) getUserProfile:(NSDictionary *) params;

-(FTTask *) getOffersTabDetailData:(NSString *) city offer:(NSString *) offer;

-(FTTask *)getMyMembershipList:(NSString *) param;

-(FTTask *) getUserCategories:(NSDictionary *) params;

-(FTTask *) getAddReviewTask:(NSDictionary*)params;

-(FTTask *) getForgetPassword:(NSDictionary *) params;

-(FTTask *) getOtpVerification:(NSDictionary *) params;

-(FTTask *) getUserProfileUpdate:(NSDictionary *) params;

-(FTTask *) getTrialMembershipsVIPSessionWorkoutSessionCount:(NSDictionary *)params;

-(FTTask *) getChangePassword:(NSDictionary *) params withAuthorization:(NSDictionary *) auth;

-(FTTask *) getGoogleDirectionTask:(NSDictionary *) params;

/**

*  Used to fetch categories and associated offerings for applying filter

*

*  @param city – name of city

*

*  @return – FTTask

*/

-(FTTask *) getFilterCategoriesTagOfferingsData:(NSString *) city;

/**

*  Used to fetch sessions for a vendor on a corresponding date

*

*  @param venderId  id of Vender

*  @param date     date for when sessions are to be fetched

*

*  @return task

*/

-(FTTask *) getTrialScheduleForVenderId:(NSString *) venderId date:(NSDate *) date;

/**

*  Used to fetch sessions

*

*  @param venderId id of vender

*  @param date     date for when sessions are to be fetched

*

*  @return task

*/

-(FTTask *) getServiceScheduleForVenderId:(NSString *) venderId date:(NSDate *) date;

/**

*   Task to post bookTrial Request

*

*  @param params params to send to Server

*

*  @return task

*/

-(FTTask *) getBookTrialTask:(NSDictionary *) params;

/**

*  Task to post BookTrial Manual Request (Offline Booking)

*

*  @param params to send to Server

*

*  @return task

*/

-(FTTask *) getManualBookTrialTask:(NSDictionary *) params;

-(FTTask *) getAddBookmarksForUserId:(NSString*)userId forFinderId:(id)finderID;

-(FTTask *) getRemoveBookmarksForUserId:(NSString*)userId forFinderId:(id)finderID;

/**

*  Generate Temp Order Task

*

*  @param params payload

*

*  @return task

*/

-(FTTask *) getGenerateTempOrderTask:(NSDictionary *) params;

/**

*  Generate COD Order Task

*

*  @param params payload

*

*  @return task

*/

-(FTTask *) getGenerateCODOrderTask:(NSDictionary *) params;

/**

*  Landing Callback Order Task

*

*  @param params payload

*

*  @return task

*/

-(FTTask *) getLandingCallbackOrderTask:(NSDictionary *) params;

-(FTTask *) sendDeviceToken:(NSDictionary *) params;

/**** New method added to capture payment*******/

-(FTTask *) capturePaymentSuccess:(NSDictionary *) params;

/******Login Home************/

-(FTTask *)getLoginHomeData:(NSDictionary *) params CityName:(NSString *)cityName;

/**** Trials List*******/

-(FTTask *)getUpcomingTrialsData:(NSDictionary *) params;

-(FTTask *)trialAction: (NSDictionary *) params Action:(NSString *) trial_action forTrialID :(NSString *)trialId;

-(FTTask *)getTrialDetailsPageDataForTrialId:(int) trialId;

-(FTTask *)eventAttendNotAttendForTrialWith:(NSDictionary *) params;

@end

RequestManager.m

#import “RequestManager.h”

#import “FTGenericHTTPGetTask.h”

#import “FTGenericHTTPPostTask.h”

#import “FTGenericHTTPPutTask.h”

#import “FTGenericHTTPDeleteTask.h”

#import <AdSupport/AdSupport.h>

#import “FTTaskProcessor.h”

#import “NetworkConstants.h”

#import “Helper.h”

//#import “MyMembershipModel.h”

static RequestManager *sharedInstance;

@implementation RequestManager

#pragma mark – Lifecycle

+ (RequestManager *) sharedInstance {

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

sharedInstance = [[RequestManager alloc] init];

});

return sharedInstance;

}

#pragma mark – Public

– (FTTask *)createTask:(id)inputParams type:(FTTaskType)type optionalParams:(NSDictionary *)optionalParams withClassName:(NSString *) className {

    FTTask *task = nil;

    switch (type)

    {

        case GENERIC_HTTP_GET:{

            task = [[FTGenericHTTPGetTask alloc] init];

            break;

        }

        case GENERIC_HTTP_POST:{

            task = [[FTGenericHTTPPostTask alloc] init];

            break;

        }

        case GENERIC_HTTP_DELETE:{

            task = [[FTGenericHTTPDeleteTask alloc] init];

            break;

        }

        case GENERIC_HTTP_PUT:

        default:

            task = [[FTGenericHTTPPutTask alloc] init];

            break;

    }

    task.type = type;

    task.taskParams = inputParams;

    task.className = className;

    task.optionalParams=optionalParams;

    

    return task;

}

-(FTTask *)createRankFinderTask:(NSDictionary *)params{

    FTTask *rankFinderTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    rankFinderTask.url = [NetworkConstants getRankFinderUrl];

    [[FTTaskProcessor sharedInstance] execute:rankFinderTask];

    return rankFinderTask;

}

-(FTTask *)createKeywordSearchTask:(NSDictionary *)params{

    FTTask *keywordSearchText = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    keywordSearchText.url = [NetworkConstants getKeywordSearchUrl];

    [[FTTaskProcessor sharedInstance] execute:keywordSearchText];

    return keywordSearchText;

}

-(FTTask *)createAutoSuggestedSearchTask:(NSDictionary *)params{

    FTTask *autoSuggestedSearchTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”FTAutoSuggestedSearchJsonModel”];

    autoSuggestedSearchTask.url = [NetworkConstants getAutoSuggestedUrl];

    [[FTTaskProcessor sharedInstance] execute:autoSuggestedSearchTask];

    return autoSuggestedSearchTask;

}

-(FTTask *)createAutoSuggestedSearchLocation:(NSDictionary *)params searchString:(NSString *)asearchString {

    FTTask *autoSuggestedSearchTask = [self createTask:params type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”nil”];

    autoSuggestedSearchTask.url = [NetworkConstants getAutoSuggestedUrlHomeScreen:asearchString];

    [[FTTaskProcessor sharedInstance] execute:autoSuggestedSearchTask];

    return autoSuggestedSearchTask;

}

-(FTTask *) getMyMembershipList:(NSString *)param{

        FTTask *membershipList = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”MyMembershipModel”];

       membershipList.url = [NetworkConstants getMyMembershipListUrl:param];

     //   membershipList.url = @”http://a1.fitternity.com/orderhistory/ut.mehrotra@gmail.com“;

        [[FTTaskProcessor sharedInstance] execute:membershipList];

        return membershipList;

    }

-(FTTask *) getRegistrationTask:(NSDictionary *) params{

    FTTask *registration = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    registration.url = [NetworkConstants getCustomerRegisterUrl];

    [[FTTaskProcessor sharedInstance] execute:registration];

    return registration;

}

-(FTTask *) getUserLoginTask:(NSDictionary *) params{

    FTTask *login = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    login.url = [NetworkConstants getCustomerLoginUrl];

    [[FTTaskProcessor sharedInstance] execute:login];

    return login;

}

-(FTTask *)postNotificationSettings:(NSDictionary *)params optionalParams:(NSDictionary *)aOptionalParams

{

    FTTask *notificationSetting = [self createTask:params type:GENERIC_HTTP_POST optionalParams:aOptionalParams withClassName:@”nil”];

    notificationSetting.url = [NetworkConstants postNotificationSetting];

    [[FTTaskProcessor sharedInstance] execute:notificationSetting];

    return notificationSetting;

}

-(FTTask *) getHomeScreenData:(NSString *) city{

    FTTask *homeTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”HomeScreenModel”];

    homeTask.url = [NetworkConstants getHomeScreenDataUrl:city];

    [[FTTaskProcessor sharedInstance] execute:homeTask];

    return homeTask;

}

-(FTTask *)vendorDetailTask:(NSString *)vendorName

{

    FTTask *vendorDetailTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”FTJFinderDetailModel”];

    //vendorDetailTask.url = @”http://a1.fitternity.com/finderdetail/20-15-fitness-tardeo“;

    vendorDetailTask.url = [NetworkConstants getVendorDetailUrl:vendorName];

    [[FTTaskProcessor sharedInstance] execute:vendorDetailTask];

    return vendorDetailTask;

}

-(FTTask *) getFilterCategoriesTagOfferingsData:(NSString *) city{

    FTTask *filterCategoryOfferingsTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”FilterCategoryTagsModel”];

    filterCategoryOfferingsTask.url = [NetworkConstants getCategoryTagOfferingUrlForCity:city];

    [[FTTaskProcessor sharedInstance] execute:filterCategoryOfferingsTask];

    return filterCategoryOfferingsTask;

}

-(FTTask *) getFinderResults:(NSDictionary *) params{

    FTTask *finderTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    finderTask.url = [NetworkConstants getFinderResultUrl];

    [[FTTaskProcessor sharedInstance] execute:finderTask];

    return finderTask;

}

-(FTTask *) getSelectedVenderList:(NSString *) param{

    FTTask *venderList = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”SelectedVenderCollectionModel”];

    venderList.url = [NetworkConstants getSelectedVenderListUrl:param];

    [[FTTaskProcessor sharedInstance] execute:venderList];

    return venderList;

}

-(FTTask *) getTrialsList:(NSString *)param{

    FTTask *trialsList = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”TrialsListModel”];

    trialsList.url = [NetworkConstants getTrialsListUrl:param];

    [[FTTaskProcessor sharedInstance] execute:trialsList];

    return trialsList;

}

-(FTTask *) getCities{

    FTTask *cityList = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”nil”];

    cityList.url = [NetworkConstants getCityListUrl];

    [[FTTaskProcessor sharedInstance] execute:cityList];

    return cityList;

}

-(FTTask *) getArea :(NSString*)cityName

{

    FTTask *areaList = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”nil”];

    areaList.url = [NetworkConstants getAreaListUrl:cityName];

    NSLog(@”areaList.url  : %@”,areaList.url);

    [[FTTaskProcessor sharedInstance] execute:areaList];

    return areaList;

}

-(FTTask *) getTrialScheduleForVenderId:(NSString *) venderId date:(NSDate *) date{

    FTTask *trialSchdule = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”nil”];

    trialSchdule.url = [NetworkConstants getTrailScheduleUrlForVenderId:venderId date:date];

    [[FTTaskProcessor sharedInstance] execute:trialSchdule];

    return trialSchdule;

}

-(FTTask *) getServiceScheduleForVenderId:(NSString *) venderId date:(NSDate *) date{

    FTTask *serviceSchedule = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”nil”];

    serviceSchedule.url = [NetworkConstants getServiceScheduleUrlForVenderId:venderId date:date];

    [[FTTaskProcessor sharedInstance] execute:serviceSchedule];

    return serviceSchedule;

}

-(FTTask *) getBookTrialTask:(NSDictionary *) params{

    FTTask *bookTrial = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    bookTrial.url = [NetworkConstants getBookTrialUrl];

    [[FTTaskProcessor sharedInstance] execute:bookTrial];

    return bookTrial;

}

-(FTTask *) getManualBookTrialTask:(NSDictionary *) params{

    FTTask *bookTrial = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    bookTrial.url = [NetworkConstants getManualBookTrialUrl];

    [[FTTaskProcessor sharedInstance] execute:bookTrial];

    return bookTrial;

}

-(FTTask *) getAllBookmarks:(NSString*)userId{

    FTTask *bookMarkList = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”FTJBookMarkFinder”];

    bookMarkList.url = [NetworkConstants getAllBookmarkUrl:userId];

    [[FTTaskProcessor sharedInstance] execute:bookMarkList];

    return bookMarkList;

}

-(FTTask *) getRemoveBookmarksForUserId:(NSString*)userId forFinderId:(id)finderID{

    FTTask *removeBookMark = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”FTJBookMarkFinder”];

    removeBookMark.url = [NetworkConstants getRemoveBookmarkUrlForUserId:userId forServiceId:finderID];

    [[FTTaskProcessor sharedInstance] execute:removeBookMark];

    return removeBookMark;

}

-(FTTask *) getAddBookmarksForUserId:(NSString*)userId forFinderId:(id)finderID{

    FTTask *addBookmark = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”FTJBookMarkFinder”];

    addBookmark.url = [NetworkConstants getAddBookmarkUrlForUserId:userId forServiceId:finderID];

    [[FTTaskProcessor sharedInstance] execute:addBookmark];

    return addBookmark;

}

-(FTTask *) getOffersTabData:(NSString *) city{

    FTTask *offersData = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”OffersModel”];

    offersData.url = [NetworkConstants getOffersTabUrl:city];

    [[FTTaskProcessor sharedInstance] execute:offersData];

    return offersData;

}

-(FTTask *) getGenerateTempOrderTask:(NSDictionary *) params{

    FTTask *tempOrderTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    tempOrderTask.url = [NetworkConstants getGenerateTempOrderUrl];

    [[FTTaskProcessor sharedInstance] execute:tempOrderTask];

    return tempOrderTask;

}

-(FTTask *) getGenerateCODOrderTask:(NSDictionary *) params{

    FTTask *codOrderTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    codOrderTask.url = [NetworkConstants getGenerateCODOrderUrl];

    [[FTTaskProcessor sharedInstance] execute:codOrderTask];

    return codOrderTask;

}

-(FTTask *) getLandingCallbackOrderTask:(NSDictionary *) params{

    FTTask *landingCallbackOrderTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    landingCallbackOrderTask.url = [NetworkConstants getLandingCallbackUrl];

    [[FTTaskProcessor sharedInstance] execute:landingCallbackOrderTask];

    return landingCallbackOrderTask;

}

-(FTTask *) getRequestCallBackTask:(NSDictionary *) params{

    FTTask *callBack = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    callBack.url = [NetworkConstants getRequestCallBackUrl];

    [[FTTaskProcessor sharedInstance] execute:callBack];

    return callBack;

}

-(FTTask *) getUserProfile:(NSDictionary *) params

{

    FTTask *profile = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:params withClassName:@”nil”];

    profile.url = [NetworkConstants getUserProfileUrl];

    [[FTTaskProcessor sharedInstance] execute:profile];

    return profile;

}

-(FTTask *) getOffersTabDetailData:(NSString *) city offer:(NSString *) offer{

    FTTask *offerDetail = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”OffersListModel”];

    offerDetail.url = [NetworkConstants getOffersTabDetailUrl:city offer:offer];

    [[FTTaskProcessor sharedInstance] execute:offerDetail];

    return offerDetail;

}

-(FTTask *) getAddReviewTask:(NSDictionary*)params{

    FTTask *reviewTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    reviewTask.url = [NetworkConstants getReviewTask];

    [[FTTaskProcessor sharedInstance] execute:reviewTask];

    return reviewTask;

}

-(FTTask *) getUserCategories:(NSDictionary *) params{

    FTTask *categories = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    categories.url = [NetworkConstants getCategoriesUrl];

    [[FTTaskProcessor sharedInstance] execute:categories];

    return categories;

}

-(FTTask *) getChangePassword:(NSDictionary *) params withAuthorization:(NSDictionary *) auth{

    FTTask *chngPaswd = [self createTask:params type:GENERIC_HTTP_POST optionalParams:auth withClassName:@”nil”];

    chngPaswd.url = [NetworkConstants getChangePasswordUrl];

    [[FTTaskProcessor sharedInstance] execute:chngPaswd];

    return chngPaswd;

}

-(FTTask *) getForgetPassword:(NSDictionary *) params{

    FTTask *forgetPswd = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    forgetPswd.url = [NetworkConstants getForgotPassword];

    [[FTTaskProcessor sharedInstance] execute:forgetPswd];

    return forgetPswd;

}

-(FTTask *) getOtpVerification:(NSDictionary *) params{

    FTTask *otpPswd = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    otpPswd.url = [NetworkConstants getOtpUrl];

    [[FTTaskProcessor sharedInstance] execute:otpPswd];

    return otpPswd;

}

-(FTTask *) getUserProfileUpdate:(NSDictionary *) params

{

    FTTask *userUpdate = [self createTask:params type:GENERIC_HTTP_POST optionalParams:params withClassName:@”nil”];

    userUpdate.url = [NetworkConstants getUserUpdateProfile];

    [[FTTaskProcessor sharedInstance] execute:userUpdate];

    return userUpdate;

}

-(FTTask *) getTrialMembershipsVIPSessionWorkoutSessionCount:(NSDictionary *)params

{

    FTTask *userUpdate = [self createTask:params type:GENERIC_HTTP_GET optionalParams:params withClassName:@”nil”];

    userUpdate.url = [NetworkConstants getTrialMembershipVipSessionWorkoutSessionEmail];

    [[FTTaskProcessor sharedInstance] execute:userUpdate];

    return userUpdate;

    

}

-(FTTask *) getGoogleDirectionTask:(NSDictionary *) params{

    FTTask *directionTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:@”nil”];

    directionTask.url = [NetworkConstants getGoogleDirectionUrlForParams:params];

    [[FTTaskProcessor sharedInstance] execute:directionTask];

    return directionTask;

}

-(FTTask *) sendDeviceToken:(NSDictionary *) params{

    FTTask *sendDeviceToken = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    sendDeviceToken.url = [NetworkConstants sendDeviceTokenURL];

    [[FTTaskProcessor sharedInstance] execute:sendDeviceToken];

    return sendDeviceToken;

}

/**** New method added to capture payment*******/

-(FTTask *) capturePaymentSuccess:(NSDictionary *) params{

    FTTask *capturePayment = [self createTask:params type:GENERIC_HTTP_POST optionalParams:nil withClassName:@”nil”];

    capturePayment.url = [NetworkConstants trackPaymentSuccess];

    [[FTTaskProcessor sharedInstance] execute:capturePayment];

    return capturePayment;

}

-(FTTask *)getUpcomingTrialsData:(NSDictionary *) params

{

    FTTask *trialTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:params withClassName:nil];

    trialTask.url = [NetworkConstants getUpcomingTrials];

    [[FTTaskProcessor sharedInstance] execute:trialTask];

    return trialTask;

}

-(FTTask *)getLoginHomeData:(NSDictionary *) params CityName:(NSString *)cityName

{

    //+(NSString *) getHomeScreenDataUrl:(NSString *)city

    FTTask *homeTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:params withClassName:nil];

    homeTask.url = [NetworkConstants getHomeScreenDataUrl:cityName];

    [[FTTaskProcessor sharedInstance] execute:homeTask];

    return homeTask;

}

-(FTTask *)trialAction: (NSDictionary *) params Action:(NSString *) trial_action forTrialID :(NSString *)trialId

{

    FTTask *trialTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:params withClassName:nil];

    trialTask.url = [NetworkConstants performTrialAction:trial_action forTrialID:trialId];

    [[FTTaskProcessor sharedInstance] execute:trialTask];

    return trialTask;

}

-(FTTask *)getTrialDetailsPageDataForTrialId:(int) trialId

{

    FTTask *trialTask = [self createTask:nil type:GENERIC_HTTP_GET optionalParams:nil withClassName:nil];

    trialTask.url = [NetworkConstants getTrialPageDetailsForId:trialId];

    [[FTTaskProcessor sharedInstance] execute:trialTask];

    return trialTask;

}

-(FTTask *)eventAttendNotAttendForTrialWith:(NSDictionary *) params

{

    FTTask *trialTask = [self createTask:params type:GENERIC_HTTP_POST optionalParams:params withClassName:nil];

    trialTask.url = [NetworkConstants eventAttendedNotAttended];

    [[FTTaskProcessor sharedInstance] execute:trialTask];

    return trialTask;

}

@end

Download Sample Project From Github

Hit API get Responce with NSUrlSession

ViewController.m

#import “NetworkManager.h”

#import “Utility.h”

– (IBAction)buttonActionHitAPIPostMethod:(id)sender {

    

    

     NSDictionary *mapData = [[NSMutableDictionary alloc] initWithObjectsAndKeys:

     @”email”, @”identity”,

     @”amit@yopmail.com”, @”email”,

     @”123456″, @”password”,

     nil];

     

     

     

     

     [[NetworkManager sharedNetworkManager]hitAPIPOSTMethodURL:@”http://a1.fitternity.com/customerlogin&#8221; AdditionalHeaderParameters:nil parameters:mapData completionHandlerSuccess:^(NSDictionary *responseDictionary) {

     NSLog(@”%@”,responseDictionary);

     } completionHandlerFailure:^(NSError *error) {

     NSLog(@”%@”,error);

     }];

     

}

– (IBAction)buttonActionHitAPIGetMethod:(id)sender {

    

    //http://shagunn.info/cherishws/mobileapi/listMenus

    

    [[NetworkManager sharedNetworkManager]hitAPIGETMethodURL:@”http://shagunn.info/cherishws/mobileapi/listMenus&#8221; AdditionalHeaderParameters:nil completionHandlerSuccess:^(NSDictionary *responseDictionary) {

        NSLog(@”%@”,responseDictionary);

    } completionHandlerFailure:^(NSError *error) {

        NSLog(@”%@”,error);

    }];

    

    

}

NetworkManager.h

#import <Foundation/Foundation.h>

#import “Utility.h”

@interface NetworkManager : NSObject<NSURLSessionDelegate>

+ (NetworkManager *)sharedNetworkManager;

– (void)hitAPIPOSTMethodURL:(NSString *)stringURL AdditionalHeaderParameters:(NSDictionary *)dictionaryAdditionalHeaderParameters parameters:(NSDictionary *)dictionaryParameters completionHandlerSuccess:(void (^)(NSDictionary *responseDictionary))success completionHandlerFailure:(void (^)(NSError *error))failure;

– (void)hitAPIGETMethodURL:(NSString *)stringURL AdditionalHeaderParameters:(NSDictionary *)dictionaryAdditionalHeaderParameters completionHandlerSuccess:(void (^)(NSDictionary *responseDictionary))success completionHandlerFailure:(void (^)(NSError *error))failure;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    

    static NetworkManager *sharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[NetworkManager alloc]init];

    });

    return sharedInstance;

    

    //    static NetworkManager *sharedNetworkManager = nil;

    //    static dispatch_once_t oncePredicate;

    //    dispatch_once(&oncePredicate, ^{

    //

    //        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

    //        [sharedNetworkManager setupServerConnection];

    //        [sharedNetworkManager.reachabilityManager startMonitoring];

    //

    //    });

    //

    //    return sharedNetworkManager;

    

}

– (void)hitAPIPOSTMethodURL:(NSString *)stringURL AdditionalHeaderParameters:(NSDictionary *)dictionaryAdditionalHeaderParameters parameters:(NSDictionary *)dictionaryParameters completionHandlerSuccess:(void (^)(NSDictionary *responseDictionary))success completionHandlerFailure:(void (^)(NSError *error))failure

{

    if ([Utility isInternetConnected_ShowPopupIfNotConnected:YES])

    {

        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

        sessionConfiguration.HTTPAdditionalHeaders = dictionaryAdditionalHeaderParameters;

        NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

        NSURL *url = [NSURL URLWithString:stringURL];

        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url

                                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                              timeoutInterval:60.0];

        

        //        [urlRequest addValue:@”application/json” forHTTPHeaderField:@”Content-Type”];

        //        [urlRequest addValue:@”application/json” forHTTPHeaderField:@”Accept”];

        

        [urlRequest setHTTPMethod:@”POST”];

        

        /*

         NSString *stringPost = [dictionaryParameters urlEncodedString];

         NSData *dataPost = [stringPost dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

         NSString *stringPostLength = [NSString stringWithFormat:@”%lu”,(unsigned long)[dataPost length]];

         [urlRequest setValue:stringPostLength forHTTPHeaderField:@”Content-Length”];

         //        [request setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Content-Type”];

         [urlRequest setValue:@”application/form-data” forHTTPHeaderField:@”Content-Text”];

         [urlRequest setHTTPBody:dataPost];

         */

        

        //        for Body – raw – Json(application/json)

        NSError *error;

        NSData *dataPost = [NSJSONSerialization dataWithJSONObject:dictionaryParameters options:0 error:&error];

        [urlRequest setHTTPBody:dataPost];

        

        

        NSURLSessionDataTask *urlSessionDataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

            if (error == nil)

            {

                NSDictionary * dictionaryJson  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

                success(dictionaryJson);

            }

            else

            {

                failure(error);

            }

        }];

        [urlSessionDataTask resume];

    }

}

– (void)hitAPIGETMethodURL:(NSString *)stringURL AdditionalHeaderParameters:(NSDictionary *)dictionaryAdditionalHeaderParameters completionHandlerSuccess:(void (^)(NSDictionary *responseDictionary))success completionHandlerFailure:(void (^)(NSError *error))failure

{

    if ([Utility isInternetConnected_ShowPopupIfNotConnected:YES])

    {

        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

        sessionConfiguration.HTTPAdditionalHeaders = dictionaryAdditionalHeaderParameters;

        NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

        NSURL *url = [NSURL URLWithString:stringURL];

        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url

                                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                              timeoutInterval:60.0];

        

        //        [urlRequest addValue:@”application/json” forHTTPHeaderField:@”Content-Type”];

        //        [urlRequest addValue:@”application/json” forHTTPHeaderField:@”Accept”];

        

        [urlRequest setHTTPMethod:@”GET”];

        NSURLSessionDataTask *urlSessionDataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

            if (error == nil)

            {

                NSDictionary * dictionaryJson  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

                success(dictionaryJson);

            }

            else

            {

                failure(error);

            }

        }];

        [urlSessionDataTask resume];

    }

}

@end

Utility.h

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

#import “Reachability.h”

#import “Constant.h”

#import <objc/runtime.h>

typedef NS_ENUM(NSUInteger , WeekDay){

    SUNDAY = 1,

    MONDAY,

    TUESDAY,

    WEDNESDAY,

    THURSDAY,

    FRIDAY,

    SATURDAY

};

@interface Utility : NSObject

+ (BOOL)isInternetConnected_ShowPopupIfNotConnected:(BOOL)showPopup;

@end

Utility.m

#import “Utility.h”

@implementation Utility

+ (BOOL)isInternetConnected_ShowPopupIfNotConnected:(BOOL)showPopup

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

    // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Check Internet Connection”);

        

        if (showPopup)

        {

            UIAlertController *anAlertController=[UIAlertController alertControllerWithTitle:@”Check Internet Connection” message:nil preferredStyle:UIAlertControllerStyleAlert];

            

            id rootViewController=[UIApplication sharedApplication].delegate.window.rootViewController;

            if([rootViewController isKindOfClass:[UINavigationController class]])

            {

                rootViewController=[((UINavigationController *)rootViewController).viewControllers objectAtIndex:0];

            }

            

            UIAlertAction *alertActionOK = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                NSLog(@”OK”);

            }];

            

            [anAlertController addAction:alertActionOK];

            

            [rootViewController presentViewController:anAlertController animated:YES completion:^{

                NSLog(@”After Completion Code”);

            }];

        }

        return NO;

    }

    

}

+ (NSString *)getDateFormatFromDateString:(NSString *)dateAPI withFormat:(NSDateFormatter *)wFormat toFormat:(NSDateFormatter *)tFormat{

    

    NSDate *dated = [wFormat dateFromString:dateAPI];

    

    NSString *newDate = [tFormat stringFromDate:dated];

    

    return  newDate;

}

+ (NSDate *)dateFromString:(NSString *)dateString withFormat:(NSString *)dateFormat{

    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];

    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@”IST”]];

    // [formatter setLocale:[NSLocale systemLocale]];

    [formatter setDateFormat:dateFormat];

    /*** exception crash issue******/

    if([formatter dateFromString:dateString]==nil)

        

        return [NSDate date];

    

    return  [formatter dateFromString:dateString];

    

    

}

+ (NSString*)stringFromDate:(NSDate*)date inFormat:(NSString*)requiredFormat{

    

    NSDateFormatter* df = [[NSDateFormatter alloc]init];

    [df setDateFormat:requiredFormat];

    return  [df stringFromDate:date];

    

}

+ (NSString *)stringByStrippingHTML:(NSString *)htmlString

{

    NSRange r;

    while ((r = [htmlString rangeOfString:@”<[^>]+>” options:NSRegularExpressionSearch]).location != NSNotFound)

        htmlString = [htmlString stringByReplacingCharactersInRange:r withString:@””];

    

    return htmlString;

}

+ (NSString *)stringByStrippingHTMLListTags:(NSString *)htmlString

{

    NSString *removeTag0 = [htmlString stringByReplacingOccurrencesOfString:@” “ withString:@””];

    NSString *removeTag1 = [removeTag0 stringByReplacingOccurrencesOfString:@”<ul><li>” withString:@” “];

    NSString *removeTag2 = [removeTag1 stringByReplacingOccurrencesOfString:@”</li><li>” withString:@” “];

    NSString *removeTag3 = [removeTag2 stringByReplacingOccurrencesOfString:@”</li></ul>” withString:@” “];

    NSString *removeTag4 = [removeTag3 stringByReplacingOccurrencesOfString:@”&nbsp;” withString:@” “];

    NSString *removeTag5 = [removeTag4 stringByReplacingOccurrencesOfString:@” and “ withString:@””];

    NSString *removeTag6 = [removeTag5 stringByReplacingOccurrencesOfString:@”<strong>” withString:@””];

    NSString *removeTag7 = [removeTag6 stringByReplacingOccurrencesOfString:@”</strong>” withString:@””];

    NSString *removeTag8 = [removeTag7 stringByReplacingOccurrencesOfString:@”<p>” withString:@””];

    NSString *removeTag9 = [removeTag8 stringByReplacingOccurrencesOfString:@”</p><p>” withString:@” “];

    NSString *removeTag10 = [removeTag9 stringByReplacingOccurrencesOfString:@”</p>” withString:@” “];

    NSString *removeTag11 = [removeTag10 stringByReplacingOccurrencesOfString:@”‘” withString:@”‘”];

    NSString *removeTag12 = [removeTag11 stringByReplacingOccurrencesOfString:@”&amp;” withString:@”&”];

    

    return removeTag12;

}

+ (NSString *)stringByStrippingHTMLTags:(NSString *)htmlString

{

    NSString *removeTag1 = [htmlString stringByReplacingOccurrencesOfString:@”<ul><li>” withString:@” “];

    NSString *removeTag2 = [removeTag1 stringByReplacingOccurrencesOfString:@”</li><li>” withString:@” “];

    NSString *removeTag3 = [removeTag2 stringByReplacingOccurrencesOfString:@”</li></ul>” withString:@” “];

    NSString *removeTag4 = [removeTag3 stringByReplacingOccurrencesOfString:@”&nbsp;” withString:@” “];

    NSString *removeTag5 = [removeTag4 stringByReplacingOccurrencesOfString:@” and “ withString:@””];

    NSString *removeTag6 = [removeTag5 stringByReplacingOccurrencesOfString:@”<strong>” withString:@””];

    NSString *removeTag7 = [removeTag6 stringByReplacingOccurrencesOfString:@”</strong>” withString:@””];

    NSString *removeTag8 = [removeTag7 stringByReplacingOccurrencesOfString:@”<p>” withString:@””];

    NSString *removeTag9 = [removeTag8 stringByReplacingOccurrencesOfString:@”</p>” withString:@””];

    NSString *removeTag10 = [removeTag9 stringByReplacingOccurrencesOfString:@”</p><p>” withString:@” “];

    NSString *removeTag11 = [removeTag10 stringByReplacingOccurrencesOfString:@”‘” withString:@”‘”];

    NSString *removeTag12 = [removeTag11 stringByReplacingOccurrencesOfString:@”&amp;” withString:@”&”];

    

    return removeTag12;

}

+ (NSArray<NSString *> *)stringByStrippingByList:(NSString *)htmlString

{

    NSString *removeTag1 = [htmlString stringByReplacingOccurrencesOfString:@”<ul>” withString:@””];

    NSString *removeTag2 = [removeTag1 stringByReplacingOccurrencesOfString:@”</ul>” withString:@””];

    NSString *removeTag3 = [removeTag2 stringByReplacingOccurrencesOfString:@”<li>” withString:@””];

    NSString *removeTag4 = [removeTag3 stringByReplacingOccurrencesOfString:@”<p>” withString:@””];

    NSString *removeTag5 = [removeTag4 stringByReplacingOccurrencesOfString:@”</p>” withString:@””];

    

    NSString *removeTag6 = [removeTag5 stringByReplacingOccurrencesOfString:@”&nbsp;” withString:@””];

    

    NSArray<NSString *> *splittedStrings = [removeTag6 componentsSeparatedByString:@”</li>”];

    

    return [splittedStrings filteredArrayUsingPredicate:

            [NSPredicate predicateWithFormat:@”length > 0″]];

}

+ (BOOL)isValidEmail:(NSString *)checkString

{

    BOOL stricterFilter = NO;

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

}

+ (BOOL)isValidPhone:(NSString *)checkString

{

    NSString *phoneRegex = @”^((\\+)|(00))[0-9]{6,14}$”;

    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@”SELF MATCHES %@”, phoneRegex];

    return [phoneTest evaluateWithObject:checkString];

}

+ (UIActivityIndicatorView *)getActivityView:(UIView *)parentView withStyle:(UIActivityIndicatorViewStyle )style

{

    

    UIActivityIndicatorView *activityIndicator= [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];

    activityIndicator.tag=100;

    activityIndicator.center = parentView.center;

    activityIndicator.activityIndicatorViewStyle = style;

    CGAffineTransform transform = CGAffineTransformMakeScale(1.75f, 1.75f);

    activityIndicator.transform = transform;

    [parentView addSubview:activityIndicator];

    [parentView bringSubviewToFront:activityIndicator];

    return  activityIndicator;

}

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

+ (NSArray*)timeUnitPassedbetween:(NSDate*)laterDate andPreviousDate:(NSDate*)previousDate{

    

    NSDate *startDate = previousDate;

    NSDate *endDate = laterDate;

    

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth | NSCalendarUnitHour | NSCalendarUnitMinute

                                                        fromDate:startDate

                                                          toDate:endDate

                                                         options:NSCalendarWrapComponents];

    

    NSInteger year = [components year];

    NSInteger month = [components month];

    // NSInteger week = [components weekday];

    NSInteger days = [components day];

    NSInteger hour = [components hour];

    NSInteger minutes = [components minute];

    NSString *stringToUse;

    if (year > 0) {

        if (year==1) {

            stringToUse = @”year”;

        }else{

            stringToUse = @”years”;

        }

        return [NSArray arrayWithObjects:[NSNumber numberWithInteger:year],stringToUse, nil];

    }if (month>0) {

        if (year==1) {

            stringToUse = @”month”;

        }else{

            stringToUse = @”months”;

        }

        return [NSArray arrayWithObjects:[NSNumber numberWithInteger:month],stringToUse, nil];

    }

    if (days>0) {

        if (days>7) {

            if (days>14) {

                stringToUse = @”weeks”;

            }else{

                stringToUse= @”week”;

            }

            return [NSArray arrayWithObjects:[NSNumber numberWithInteger:days%7],stringToUse,nil];

        }else{

            if (days == 1) {

                stringToUse = @”day”;

            }else{

                stringToUse = @”days”;

            }

            return [NSArray arrayWithObjects:[NSNumber numberWithInteger:days],stringToUse,nil];

        }

    }if (hour>0) {

        if (hour == 1) {

            stringToUse = @”hour”;

        }else{

            stringToUse = @”hours”;

        }

        return [NSArray arrayWithObjects:[NSNumber numberWithInteger:hour],stringToUse,nil];

    }

    if (minutes>=0) {

        if (minutes <= 1) {

            stringToUse = @”minute”;

        }else{

            stringToUse = @”minutes”;

        }

    }

    return [NSArray arrayWithObjects:[NSNumber numberWithInteger:minutes],stringToUse,nil];

    

    

}

+ (NSDate *)addDays:(NSInteger)days toDate:(NSDate *)originalDate

{

    NSDateComponents *components= [[NSDateComponents alloc] init];

    [components setDay:days];

    NSCalendar *calendar = [NSCalendar currentCalendar];

    return [calendar dateByAddingComponents:components toDate:originalDate options:0];

}

+ (NSInteger)dayOfMonth:(NSDate *)date

{

    NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];

    

    NSInteger dayOfMonth = [comps day];

    return dayOfMonth;

}

+ (NSInteger)weekDayOfDate:(NSDate *)date

{

    NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:date];

    

    NSInteger dayOfMonth = [comps weekday];

    return dayOfMonth;

    

}

+ (NSString *)monthOfDate:(NSDate *)date

{

    //    NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:date];

    //

    //    NSString *monthDate = [comps month];

    

    NSDateFormatter *format = [[NSDateFormatter alloc] init];

    [format setDateFormat:@”MMM”];

    // NSDate *now = [[NSDate alloc] init];

    NSString *dateString = [format stringFromDate:date];

    return dateString;

    

    // return monthDate;

    

}

+ (NSString *)getSortWeekDayFromDate:(NSDate *)date

{

    NSInteger weekDay = [self weekDayOfDate:date];

    NSString *sortWeekDayName = @””;

    switch (weekDay) {

        case 1:

            // Sunday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_SUNDAY;

            break;

        case 2:{

            // Monday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_MONDAY;

        }

            break;

        case 3:

            // Tuesday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_TUESDAY;

            break;

        case 4:{

            // Wednesday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_WEDNESDAY;

        }

            break;

        case 5:

            // Thursday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_THURSDAY;

            break;

        case 6:{

            // Friday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_FRIDAY;

        }

            break;

        case 7:{

            // Saturday

            sortWeekDayName = FT_UPCOMING_CLASSES_SESSION_SORT_WEEKNAME_SATURDAY;

        }

            break;

        default:

            break;

    }

    return sortWeekDayName;

}

+ (NSString *)suffixForDay:(NSInteger)day{

    // Finding suffix for date

    NSString *suffix_string = @”|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st”;

    NSArray *suffixes = [suffix_string componentsSeparatedByString: @”|”];

    NSString *suffix = [suffixes objectAtIndex:day];

    return suffix;

}

+ (NSDate *)combineDateComponentFromDate:(NSDate *)date1 timeComponentFromDate:(NSDate *)date2

{

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@”IST”]];

    

    // Extract date components into components1

    NSDateComponents *components1 = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay

                                                fromDate:date1];

    

    // Extract time components into components2

    NSDateComponents *components2 = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond

                                                fromDate:date2];

    

    // Combine date and time into components3

    NSDateComponents *components3 = [[NSDateComponents alloc] init];

    

    [components3 setYear:components1.year];

    [components3 setMonth:components1.month];

    [components3 setDay:components1.day];

    

    [components3 setHour:components2.hour];

    [components3 setMinute:components2.minute];

    [components3 setSecond:components2.second];

    

    // Generate a new NSDate from components3.

    NSDate *combinedDate = [calendar dateFromComponents:components3];

    // combinedDate contains both your date and time!

    return combinedDate;

}

+ (NSUInteger )getWeekdayFromDate:(NSDate *)date

{

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *comps = [gregorian components:NSCalendarUnitWeekday fromDate:date];

    NSUInteger weekday = [comps weekday];

    return weekday;

}

+(NSDictionary *)getBase64DecodedDictionary:(NSString *)base64String

{

    

    NSArray *stringData = [base64String componentsSeparatedByString:@”.”];

    NSData *rawData = [[NSData alloc] initWithBase64EncodedString:stringData[1] options:0];

    

    NSString *decodedString = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];

    NSData *objectData = [decodedString dataUsingEncoding:NSUTF8StringEncoding];

    NSError* error;

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData

                                                         options:NSJSONReadingMutableContainers

                                                           error:&error];

    return json;

}

+ (NSString *)deviceUUID

{

    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];

}

+ (NSUInteger)getWeekDayNumber:(NSString *)weekday

{

    NSUInteger day = 0;

    if([weekday isEqualToString:@”sunday”]){

        day = SUNDAY;

    }else if([weekday isEqualToString:@”monday”]){

        day = MONDAY;

    }else if([weekday isEqualToString:@”tuesday”]){

        day = TUESDAY;

    }else if([weekday isEqualToString:@”wednesday”]){

        day = WEDNESDAY;

    }else if([weekday isEqualToString:@”thursday”]){

        day = THURSDAY;

    }else if([weekday isEqualToString:@”friday”]){

        day = FRIDAY;

    }else if([weekday isEqualToString:@”saturday”]){

        day = SATURDAY;

    }

    return day;

}

+ (NSString *)trimString_RemoveWhiteSpaceFromString:(NSString *)string

{

    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        const char* name = property_getName (var);

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    free(vars);

    return descriptionString;

}

@end

Download Sample Project From Github

Fly Over Slider Menu

ViewController.h

#import <UIKit/UIKit.h>

#import “FlyOverSideMenuView.h”

#import “FirstViewController.h”

#import “SecondViewController.h”

@interface ViewController : UIViewController<BTSimpleSideMenuDelegate>

@property(nonatomic)FlyOverSideMenuView *sideMenu;

– (IBAction)buttonActionShowSliderMain:(id)sender;

– (IBAction)buttonActionBackMain:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    //    sideMenu = [[BTSimpleSideMenu alloc]initWithItemTitles:@[@”One”, @”Two”, @”Three”, @”Four”,@”Five”, @”Six”, @”Seven”]

    //                                             andItemImages:@[

    //                                                             [UIImage imageNamed:@”icon1.jpeg”],

    //                                                             [UIImage imageNamed:@”icon2.jpeg”],

    //                                                             [UIImage imageNamed:@”icon3.jpeg”],

    //                                                             [UIImage imageNamed:@”icon4.jpeg”],

    //                                                             [UIImage imageNamed:@”icon5.jpeg”]

    //                                                             ]

    //                                       addToViewController:self];

    

    

    FlyOverSideMenuItem *item1 = [[FlyOverSideMenuItem alloc]initWithTitle:@”One”

                                                               image:[UIImage imageNamed:@”icon1.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 1″);

                                                        }];

    

    FlyOverSideMenuItem *item2 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Two”

                                                               image:[UIImage imageNamed:@”icon2.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 2″);

                                                        }];

    

    FlyOverSideMenuItem *item3 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Three”

                                                               image:[UIImage imageNamed:@”icon3.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 3″);

                                                        }];

    

    FlyOverSideMenuItem *item4 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Four”

                                                               image:[UIImage imageNamed:@”icon4.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            NSLog(@”I am Item 4″);

                                                        }];

    

    FlyOverSideMenuItem *item5 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Five”

                                                               image:[UIImage imageNamed:@”icon5.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 5″);

                                                        }];

    

    _sideMenu = [[FlyOverSideMenuView alloc]initWithItem:@[item1, item2, item3, item4, item5] addToViewController:self];

    _sideMenu.delegate = self;

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)buttonActionShowSliderMain:(id)sender

{

    [_sideMenu toggleMenu];

}

– (IBAction)buttonActionBackMain:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

#pragma -mark BTSimpleSideMenuDelegate

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu didSelectItemAtIndex:(NSInteger)index

{

     NSLog(@”Item Cliecked : %ld”, (long)index);

    

    if (index == 0)

    {

//        ViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”ViewController”];

//        [self.navigationController pushViewController:viewControllerObject animated:YES];

        

    }

    else if (index == 1)

    {

        FirstViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”FirstViewController”];

        [self.navigationController pushViewController:viewControllerObject animated:YES];

        

    }

    else if (index == 2)

    {

        SecondViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”SecondViewController”];

        [self.navigationController pushViewController:viewControllerObject animated:YES];

    }

   

}

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu selectedItemTitle:(NSString *)title

{

    NSLog(@”Item Cliecked : %@”, title);

}

@end

FirstViewController.h

#import <UIKit/UIKit.h>

#import “FlyOverSideMenuView.h”

#import “ViewController.h”

#import “SecondViewController.h”

@interface FirstViewController : UIViewController<BTSimpleSideMenuDelegate>

@property(nonatomic)FlyOverSideMenuView *sideMenu;

– (IBAction)buttonActionShowSliderFirst:(id)sender;

– (IBAction)buttonActionBackFirst:(id)sender;

@end

FirstViewController.m

#import “FirstViewController.h”

@interface FirstViewController ()

@end

@implementation FirstViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    //    sideMenu = [[BTSimpleSideMenu alloc]initWithItemTitles:@[@”One”, @”Two”, @”Three”, @”Four”,@”Five”, @”Six”, @”Seven”]

    //                                             andItemImages:@[

    //                                                             [UIImage imageNamed:@”icon1.jpeg”],

    //                                                             [UIImage imageNamed:@”icon2.jpeg”],

    //                                                             [UIImage imageNamed:@”icon3.jpeg”],

    //                                                             [UIImage imageNamed:@”icon4.jpeg”],

    //                                                             [UIImage imageNamed:@”icon5.jpeg”]

    //                                                             ]

    //                                       addToViewController:self];

    

    FlyOverSideMenuItem *item1 = [[FlyOverSideMenuItem alloc]initWithTitle:@”One”

                                                               image:[UIImage imageNamed:@”icon1.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 1″);

                                                            

                                                        }];

    

    FlyOverSideMenuItem *item2 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Two”

                                                               image:[UIImage imageNamed:@”icon2.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 2″);

                                                            

                                                        }];

    

    FlyOverSideMenuItem *item3 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Three”

                                                               image:[UIImage imageNamed:@”icon3.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 3″);

                                                        }];

    

    FlyOverSideMenuItem *item4 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Four”

                                                               image:[UIImage imageNamed:@”icon4.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            NSLog(@”I am Item 4″);

                                                        }];

    

    FlyOverSideMenuItem *item5 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Five”

                                                               image:[UIImage imageNamed:@”icon5.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 5″);

                                                        }];

    

    

    _sideMenu = [[FlyOverSideMenuView alloc]initWithItem:@[item1, item2, item3, item4, item5] addToViewController:self];

    _sideMenu.delegate = self;

    

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)buttonActionShowSliderFirst:(id)sender {

    [_sideMenu toggleMenu];

}

– (IBAction)buttonActionBackFirst:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

#pragma -mark BTSimpleSideMenuDelegate

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu didSelectItemAtIndex:(NSInteger)index

{

    NSLog(@”Item Cliecked : %ld”, (long)index);

    

    if (index == 0)

    {

        ViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”ViewController”];

        [self.navigationController pushViewController:viewControllerObject animated:YES];

    }

    else if (index == 1)

    {

//        FirstViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”FirstViewController”];

//        [self.navigationController pushViewController:viewControllerObject animated:YES];

        

    }

    else if (index == 2)

    {

        SecondViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”SecondViewController”];

        [self.navigationController pushViewController:viewControllerObject animated:YES];

    }

    

}

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu selectedItemTitle:(NSString *)title

{

    NSLog(@”Item Cliecked : %@”, title);

}

@end

SecondViewController.h

#import <UIKit/UIKit.h>

#import “FlyOverSideMenuView.h”

#import “ViewController.h”

#import “FirstViewController.h”

@interface SecondViewController : UIViewController<BTSimpleSideMenuDelegate>

@property(nonatomic)FlyOverSideMenuView *sideMenu;

– (IBAction)buttonActionShowSliderSecond:(id)sender;

– (IBAction)buttonActionBackSecond:(id)sender;

@end

SecondViewController.m

#import “SecondViewController.h”

@interface SecondViewController ()

@end

@implementation SecondViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    //    sideMenu = [[BTSimpleSideMenu alloc]initWithItemTitles:@[@”One”, @”Two”, @”Three”, @”Four”,@”Five”, @”Six”, @”Seven”]

    //                                             andItemImages:@[

    //                                                             [UIImage imageNamed:@”icon1.jpeg”],

    //                                                             [UIImage imageNamed:@”icon2.jpeg”],

    //                                                             [UIImage imageNamed:@”icon3.jpeg”],

    //                                                             [UIImage imageNamed:@”icon4.jpeg”],

    //                                                             [UIImage imageNamed:@”icon5.jpeg”]

    //                                                             ]

    //                                       addToViewController:self];

    

    FlyOverSideMenuItem *item1 = [[FlyOverSideMenuItem alloc]initWithTitle:@”One”

                                                               image:[UIImage imageNamed:@”icon1.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 1″);

                                                            

                                                        }];

    

    FlyOverSideMenuItem *item2 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Two”

                                                               image:[UIImage imageNamed:@”icon2.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 2″);

                                                            

                                                        }];

    

    FlyOverSideMenuItem *item3 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Three”

                                                               image:[UIImage imageNamed:@”icon3.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 3″);

                                                        }];

    

    FlyOverSideMenuItem *item4 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Four”

                                                               image:[UIImage imageNamed:@”icon4.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            NSLog(@”I am Item 4″);

                                                        }];

    

    FlyOverSideMenuItem *item5 = [[FlyOverSideMenuItem alloc]initWithTitle:@”Five”

                                                               image:[UIImage imageNamed:@”icon5.png”]

                                                        onCompletion:^(BOOL success, FlyOverSideMenuItem *item) {

                                                            

                                                            NSLog(@”I am Item 5″);

                                                        }];

    

    

    _sideMenu = [[FlyOverSideMenuView alloc]initWithItem:@[item1, item2, item3, item4, item5] addToViewController:self];

    _sideMenu.delegate = self;

    

    

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)buttonActionShowSliderSecond:(id)sender {

    [_sideMenu toggleMenu];

}

– (IBAction)buttonActionBackSecond:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

#pragma -mark BTSimpleSideMenuDelegate

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu didSelectItemAtIndex:(NSInteger)index

{

    NSLog(@”Item Cliecked : %ld”, (long)index);

    

    if (index == 0)

    {

        ViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”ViewController”];

        [self.navigationController pushViewController:viewControllerObject animated:YES];

    }

    else if (index == 1)

    {

                FirstViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”FirstViewController”];

                [self.navigationController pushViewController:viewControllerObject animated:YES];

        

    }

    else if (index == 2)

    {

//        SecondViewController *viewControllerObject = [[UIStoryboard storyboardWithName:@”Main” bundle:nil] instantiateViewControllerWithIdentifier:@”SecondViewController”];

//        [self.navigationController pushViewController:viewControllerObject animated:YES];

    }

    

}

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu selectedItemTitle:(NSString *)title

{

    NSLog(@”Item Cliecked : %@”, title);

}

@end

FlyOverSideMenuView.h

#import <Foundation/Foundation.h>

#import “FlyOverSideMenuItem.h”

#import “Constant.h”

#define MAIN_VIEW_TAG 1

#define TITLE_LABLE_TAG 2

#define IMAGE_VIEW_TAG 3

@class FlyOverSideMenuView;

@protocol BTSimpleSideMenuDelegate <NSObject>

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu didSelectItemAtIndex:(NSInteger)index;

-(void)BTSimpleSideMenu:(FlyOverSideMenuView *)menu selectedItemTitle:(NSString *)title;

@end

@interface FlyOverSideMenuView : UIView<UITableViewDelegate, UITableViewDataSource>

{

    @private

    UITableView *menuTable;

    NSArray *titleArray;

    NSArray *imageArray;

    NSArray *itemsArray;

    BOOL isOpen;

    UITapGestureRecognizer *gesture;

    UISwipeGestureRecognizer *leftSwipe, *rightSwipe;

    

}

@property (nonatomic, retain) FlyOverSideMenuItem *selectedItem;

@property(nonatomic, weak) id <BTSimpleSideMenuDelegate> delegate;

-(instancetype) initWithItem:(NSArray *)items addToViewController:(id)sender;

//-(instancetype) initWithItemTitles:(NSArray *)itemsTitle addToViewController:(id)sender;

//-(instancetype) initWithItemTitles:(NSArray *)itemsTitle andItemImages:(NSArray *)itemsImage addToViewController:(UIViewController *)sender;

-(void)show;

-(void)hide;

-(void)toggleMenu;

@end

FlyOverSideMenuView.m

#import “FlyOverSideMenuView.h”

@implementation FlyOverSideMenuView

-(instancetype) initWithItem:(NSArray *)items addToViewController:(id)sender {

    if ((self = [super init])) {

        // perform the other initialization of items.

        [self commonInit:sender];

        itemsArray = items;

    }

    return self;

}

-(instancetype)initWithItemTitles:(NSArray *)itemsTitle addToViewController:(UIViewController *)sender {

    

    if ((self = [super init])) {

        // perform the other initialization of items.

        [self commonInit:sender];

        NSMutableArray *tempArray = [[NSMutableArray alloc]init];

        for(int i = 0;i<[itemsTitle count]; i++){

            FlyOverSideMenuItem *temp = [[FlyOverSideMenuItem alloc]initWithTitle:[itemsTitle objectAtIndex:i]

                                                                      image:nil onCompletion:nil];

            [tempArray addObject:temp];

        }

        itemsArray = tempArray;

    }

    return self;

}

-(instancetype)initWithItemTitles:(NSArray *)itemsTitle andItemImages:(NSArray *)itemsImage addToViewController:(UIViewController *)sender{

    if ((self = [super init])) {

        // perform the other initialization of items.

        [self commonInit:sender];

        NSMutableArray *tempArray = [[NSMutableArray alloc]init];

        for(int i = 0;i<[itemsTitle count]; i++){

            FlyOverSideMenuItem *temp = [[FlyOverSideMenuItem alloc]initWithTitle:[itemsTitle objectAtIndex:i]

                                                                      image:[itemsImage objectAtIndex:i]

                                                               onCompletion:nil];

            [tempArray addObject:temp];

        }

        itemsArray = tempArray;

    }

    return self;

}

-(void)commonInit:(UIViewController *)sender

{

    self.frame = CGRectMake(WD, 0, WD, HT);

    self.backgroundColor = [UIColor clearColor];

    if(!sender.navigationController.navigationBarHidden)

    {

        menuTable = [[UITableView alloc]initWithFrame:CGRectMake(WD/4.32, 15, WD/1.3, HT) style:UITableViewStyleGrouped];

    }

    else

    {

        menuTable = [[UITableView alloc]initWithFrame:CGRectMake(WD/4.32, –15, WD/1.3, HT) style:UITableViewStyleGrouped];

    }

    

    [menuTable setBackgroundColor:[UIColor clearColor]];

    [menuTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    menuTable.scrollEnabled = NO;

    menuTable.delegate = self;

    menuTable.dataSource = self;

    menuTable.alpha = 0;

    isOpen = NO;

    [self addSubview:menuTable];

    

    gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toggleMenu)];

    gesture.numberOfTapsRequired = 2;

    

    leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(show)];

    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;

    

    rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(hide)];

    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;

    

    [sender.view addSubview:self];

    [sender.view addGestureRecognizer:gesture];

    [sender.view addGestureRecognizer:rightSwipe];

    [sender.view addGestureRecognizer:leftSwipe];

}

-(void)toggleMenu{

    if(!isOpen){

        [self show];

    }else {

        [self hide];

    }

}

-(void)show{

    if(!isOpen){

        [UIView animateWithDuration:0.5 animations:^{

            self.frame = CGRectMake(0, 0, WD, HT);

            menuTable.frame = CGRectMake(menuTable.frame.origin.x, menuTable.frame.origin.y+15, WD/1.3, HT);

            menuTable.alpha = 1;

        } completion:^(BOOL finished) {

            

        }];

        isOpen = YES;

    }

}

-(void)hide {

    if(isOpen){

        [UIView animateWithDuration:0.5 animations:^{

            self.frame = CGRectMake(WD, 0, WD, HT);

            menuTable.frame = CGRectMake(menuTable.frame.origin.x, menuTable.frame.origin.y15, WD/1.3, HT);

            menuTable.alpha = 0;

        }];

        isOpen = NO;

    }

}

#pragma -mark tableView Delegates

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [itemsArray count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    

    UILabel *titleLabel;

    UIImageView *imageView;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”cell”];

    

    FlyOverSideMenuItem *item = [itemsArray objectAtIndex:indexPath.row];

    

    if(cell == nil)

    {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”cell”];

        cell.backgroundColor = [UIColor whiteColor];

        

        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WD/16, HT/56.8, WD/16, HT/28.4)];

        imageView.tag = IMAGE_VIEW_TAG;

        [cell.contentView addSubview:imageView];

        

        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(WD/4.5, HT/47.3, WD/1.70, HT/37.8)];

        titleLabel.tag = TITLE_LABLE_TAG;

        titleLabel.textColor = [UIColor colorWithWhite:0.2 alpha:1];

        titleLabel.minimumFontSize = 9;

        [cell.contentView addSubview:titleLabel];

    }

    else

    {

        

        titleLabel = (UILabel *)[cell.contentView viewWithTag:TITLE_LABLE_TAG];

        imageView = (UIImageView *)[cell.contentView viewWithTag:IMAGE_VIEW_TAG];

    }

    

    titleLabel.text = item.title;

    imageView.image = item.imageView.image;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return HT/14.2;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    

    if (self.delegate && [self.delegate respondsToSelector:@selector(BTSimpleSideMenu:didSelectItemAtIndex:)])

    {

        [self.delegate BTSimpleSideMenu:self didSelectItemAtIndex:indexPath.row];

    }

    

    if (self.delegate && [self.delegate respondsToSelector:@selector(BTSimpleSideMenu:selectedItemTitle:)])

    {

        [self.delegate BTSimpleSideMenu:self selectedItemTitle:[[itemsArray objectAtIndex:indexPath.row] title]];

    }

    

    _selectedItem = [itemsArray objectAtIndex:indexPath.row];

    [self hide];

    if (_selectedItem.block) {

        BOOL success= YES;

        _selectedItem.block(success, _selectedItem);

    }

    [menuTable deselectRowAtIndexPath:indexPath animated:YES];

}

@end

FlyOverSideMenuItem.h

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@class FlyOverSideMenuItem;

typedef void (^completion)(BOOL success, FlyOverSideMenuItem *item);

@interface FlyOverSideMenuItem : NSObject

@property (nonatomic, copy) NSString *title;

@property (nonatomic, strong) UIImage *image;

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, copy) completion block;

-(id)initWithTitle:(NSString *)title image:(UIImage *)image onCompletion:(completion)completionBlock;

@end

FlyOverSideMenuItem.m

#import “FlyOverSideMenuItem.h”

@implementation FlyOverSideMenuItem

-(id)initWithTitle:(NSString *)title image:(UIImage *)image onCompletion:(completion)completionBlock;

{

    self = [super init];

    if(self)

    {

        self.title = title;

        self.image = image;

        self.block = completionBlock;

        self.imageView = [[UIImageView alloc]initWithImage:image];

        self.imageView.frame = CGRectMake(0, 0, 40, 40);

    }

    

    return self;

}

@end

Download Sample Project From Github

Custom CollectionView

HomeScreenViewController.h

#import <UIKit/UIKit.h>

#import “HomeScreenCollectionViewCell.h”

#import “Constant.h”

@interface HomeScreenViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) NSMutableArray *arrayCollectionViewData;

@property (strong, nonatomic) NSMutableArray *arrayTableViewData;

@property (strong, nonatomic) NSString *stringTableViewTitle;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionViewHomeScreen;

@property (weak, nonatomic) IBOutlet UITableView *tableViewPopUp;

@property (weak, nonatomic) IBOutlet UIView *viewPopUpBelowTable;

@end

HomeScreenViewController.m

#import “HomeScreenViewController.h”

@interface HomeScreenViewController ()

@end

@implementation HomeScreenViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [super viewDidLoad];    

    

    NSMutableArray *arrayCGPDashboardTableViewData = [[NSMutableArray alloc]init];

    arrayCGPDashboardTableViewData = (NSMutableArray *)@[@”Plan Detail”,@”Accumalated Gold”,@”Payments / Installments”,@”Pay Monthly EMI / TOPUP”];

    

    NSMutableArray *arrayMyProfileTableViewData = [[NSMutableArray alloc]init];

    arrayMyProfileTableViewData = (NSMutableArray *)@[@”Personal Detail”,@”Contact Detail”,@”Nomination Detail”,@”Change Password”];

    

    NSMutableArray *arrayBecomeaReferalTableViewData = [[NSMutableArray alloc]init];

    arrayBecomeaReferalTableViewData = (NSMutableArray *)@[@”What is referral program”,@”Reward Point Statement”];

    

    

    NSMutableArray *arrayShoppingTableViewData = [[NSMutableArray alloc]init];

    arrayShoppingTableViewData = (NSMutableArray *)@[@”Shopping”];

    

    NSMutableArray *arrayAboutTableViewData = [[NSMutableArray alloc]init];

    arrayAboutTableViewData = (NSMutableArray *)@[@”Company”,@”Brand Cherish Gold”,@”FAQ”,@”Terms & Condition”,@”Policies”];

    

    

    NSMutableArray *arrayRelationshipManagerTableViewData = [[NSMutableArray alloc]init];

    arrayRelationshipManagerTableViewData = (NSMutableArray *)@[@”RM Details”];

    

    

    NSMutableArray *arrayContactusTableViewData = [[NSMutableArray alloc]init];

    arrayContactusTableViewData = (NSMutableArray *)@[@”Contact Us”,@”Call us!”,@”Send Query”,@”Help us improve”];

    

    

    NSMutableArray *arraySocialMediaTableViewData = [[NSMutableArray alloc]init];

    arraySocialMediaTableViewData = (NSMutableArray *)@[@”Facebook”,@”Twitter”];

    

    

    NSMutableArray *arrayProposenewReferanceTableViewData = [[NSMutableArray alloc]init];

    arrayProposenewReferanceTableViewData = (NSMutableArray *)@[@”Propose Referance”,@”Status of Submitted Referances”];

   

    

    

    

    

    

    self.arrayCollectionViewData = (NSMutableArray *)@[@{@”Image”: @”a1″, @”Name”:@”CGP Dashboard”, @”Title”:@”CGP Dashboard”, @”TableData”:arrayCGPDashboardTableViewData},

                                                       @{@”Image”: @”b2″, @”Name”:@”My Profile”, @”Title”:@”My Profile”, @”TableData”:arrayMyProfileTableViewData},

                                                       @{@”Image”: @”c3″, @”Name”:@”Become a Referal”, @”Title”:@”Become a Referal”, @”TableData”:arrayBecomeaReferalTableViewData},

                                                       @{@”Image”: @”d4″, @”Name”:@”Shopping”, @”Title”:@”Shopping”, @”TableData”:arrayShoppingTableViewData},

                                                       @{@”Image”: @”e5″, @”Name”:@”About”, @”Title”:@”About”, @”TableData”:arrayAboutTableViewData},

                                                       @{@”Image”: @”f6″, @”Name”:@”Relationship Manager”, @”Title”:@”Relationship Manager”, @”TableData”:arrayRelationshipManagerTableViewData},

                                                       @{@”Image”: @”g7″, @”Name”:@”Contact us”, @”Title”:@”Contact Us”, @”TableData”:arrayContactusTableViewData},

                                                       @{@”Image”: @”h8″, @”Name”:@”Social Media”, @”Title”:@”Social Media”, @”TableData”:arraySocialMediaTableViewData},

                                                       @{@”Image”: @”i9″, @”Name”:@”Propose new Referance”, @”Title”:@”Propose New Referance”, @”TableData”:arrayProposenewReferanceTableViewData},];

    

    NSLog(@”%@”,self.arrayCollectionViewData);

    

    /*

    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];

//    (cellWidth, cellHeight)

    flow.itemSize = CGSizeMake(10, 10);

    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    flow.minimumInteritemSpacing = 0;

    flow.minimumLineSpacing = 0;

    */

    

    

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGesture:)];

    [_viewPopUpBelowTable addGestureRecognizer:tapGestureRecognizer];

    

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    _viewPopUpBelowTable.hidden = YES;

    _tableViewPopUp.hidden = YES;

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return [self.arrayCollectionViewData count];

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *stringStaticIdentifier = @”HomeScreenCollectionViewCell”;

    HomeScreenCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:stringStaticIdentifier forIndexPath:indexPath];

    [cell cellSetUpData:[self.arrayCollectionViewData objectAtIndex:indexPath.row]];

    [[cell contentView] setFrame:[cell bounds]];

    [[cell contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

    

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”%ld”,(long)indexPath.row);

    _viewPopUpBelowTable.hidden = NO;

    _tableViewPopUp.hidden = NO;

    

    _arrayTableViewData = [[_arrayCollectionViewData objectAtIndex:indexPath.row] valueForKey:@”TableData”];

    _stringTableViewTitle = [[_arrayCollectionViewData objectAtIndex:indexPath.row] valueForKey:@”Title”];

    NSLog(@”%@”,_stringTableViewTitle);

    

     _tableViewPopUp.frame = CGRectMake(self.view.center.x – ((WD/1.2)/2), self.view.center.y – (((HT/15.0*(_arrayTableViewData.count)) + HT/15.0)/2), WD/1.2, (HT/15.0*(_arrayTableViewData.count)) + HT/15.0);

    

    

//    _tableViewPopUp.translatesAutoresizingMaskIntoConstraints = YES;

//    [self.view addSubview:_tableViewPopUp];

//    // Width

//    [_tableViewPopUp addConstraint:[NSLayoutConstraint constraintWithItem:_tableViewPopUp attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:WD/1.2]];

//    // Height

//    [_tableViewPopUp addConstraint:[NSLayoutConstraint constraintWithItem:_tableViewPopUp attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:((HT/15.0*(_arrayTableViewData.count)) + HT/15.0)]];

//        // X

//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_tableViewPopUp attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];

//    // Y

//    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_tableViewPopUp attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

//    [self.view addSubview:_tableViewPopUp];

    

    

    [_tableViewPopUp reloadData];

}

#pragma mark – CollectionView FlowLayout

// Layout: Set cell size

– (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    return CGSizeMake(WD/3.5f, HT/4.1f);

}

– (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {

//    Space Between cell Vertically

    return WD/25;

}

– (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {

//    Space Between cell Horizontally

    return HT/33;

}

// Layout: Set Edges

– (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    // return UIEdgeInsetsMake(0,8,0,8);  // top, left, bottom, right

    return UIEdgeInsetsMake(0, WD/37.5, 0, WD/37.5);

}

#pragma mark – View Popup

#pragma mark – TableView Delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [_arrayTableViewData count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”cellTableView”];

    

    cell.textLabel.text = [_arrayTableViewData objectAtIndex:indexPath.row];

    return cell;

}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    return _stringTableViewTitle;

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return HT/15.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return HT/15.0;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”%ld”,(long)indexPath.row);

    _viewPopUpBelowTable.hidden = YES;

    _tableViewPopUp.hidden = YES;

}

-(void)handleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer

{

    _viewPopUpBelowTable.hidden = YES;

    _tableViewPopUp.hidden = YES;

}

@end

HomeScreenCollectionViewCell.h

#import <UIKit/UIKit.h>

#import <QuartzCore/QuartzCore.h>

@interface HomeScreenCollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UIImageView *imageViewItem;

@property (weak, nonatomic) IBOutlet UILabel *labelItemlName;

@property (weak, nonatomic) IBOutlet UIView *ViewMain;

– (void)cellSetUpData:(id)CellData;

@end

HomeScreenCollectionViewCell.m

#import “HomeScreenCollectionViewCell.h”

@implementation HomeScreenCollectionViewCell

– (void)cellSetUpData:(id)CellData

{

    NSLog(@”%@”,CellData);

    

    [_ViewMain.layer setCornerRadius:20.0f];

    _ViewMain.layer.borderColor = [UIColor grayColor].CGColor;

    _ViewMain.layer.borderWidth = 2.0f;

    [_ViewMain.layer setMasksToBounds:YES];

    

    self.imageViewItem.image = [UIImage imageNamed:[CellData valueForKey:@”Image”]];

    self.labelItemlName.text = [CellData valueForKey:@”Name”];

    

}

@end

Download Sample Project From Github

Coredata add in Existing project

ViewController.h

#import <UIKit/UIKit.h>

#import “CoreDataUtility.h”

#import “Form.h”

#import “Utility.h”

@interface ViewController : UIViewController

– (IBAction)buttonActionInsertData:(id)sender;

– (IBAction)buttonActionFetchData:(id)sender;

– (IBAction)buttonActionUpdataData:(id)sender;

– (IBAction)buttonActionDeleteData:(id)sender;

– (IBAction)buttonActionViewAllData:(id)sender;

– (IBAction)buttonActionDeleteAllData:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)buttonActionInsertData:(id)sender {

    

    {

    NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                    @”Philippe”, @”firstName”,

                                                    @”Wilson”, @”lastName”,

                                                    @”1212121212″, @”phoneNumber”,

                                                    @”California”, @”city”,

                                                    @”11″, @”rollNo”, nil];

    

    [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    {

        NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                        @”Ales”, @”firstName”,

                                                        @”Wilson”, @”lastName”,

                                                        @”1717171717″, @”phoneNumber”,

                                                        @”USA”, @”city”,

                                                        @”12″, @”rollNo”, nil];

        

        [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    {

        NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                        @”Steave”, @”firstName”,

                                                        @”Reonaldo”, @”lastName”,

                                                        @”123456790″, @”phoneNumber”,

                                                        @”California”, @”city”,

                                                        @”13″, @”rollNo”, nil];

        

        [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    

}

– (IBAction)buttonActionFetchData:(id)sender {

    

    {

   Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”11″];

    

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

    }

    

    {

        Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”12″];

        

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

        

        

    }

    {

        Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”13″];

        

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

    }

}

– (IBAction)buttonActionUpdataData:(id)sender {

    

    

    NSMutableDictionary *dictionaryStudentUpdateDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                          @”NewSteave”, @”firstName”,

                                                          @”NewReonaldo”, @”lastName”,

                                                          @”+91123456790″, @”phoneNumber”,

                                                          @”New York”, @”city”,

                                                          @”13″, @”rollNo”, nil];

    

    

    

    

    [CoreDataUtility updateData:dictionaryStudentUpdateDetail];

}

– (IBAction)buttonActionDeleteData:(id)sender {

    

    [CoreDataUtility deleteStudentDetailRollNo:@”12″];

}

– (IBAction)buttonActionViewAllData:(id)sender {

    

    NSArray *arrayAllData = [[NSArray alloc]initWithArray:[CoreDataUtility getAllRecords]];

    NSLog(@”%@”,arrayAllData);

    

    if (arrayAllData.count > 0)

    {

        for (int i = 0; i<[arrayAllData count]; i++)

        {

           NSLog(@”%@”,[[arrayAllData objectAtIndex:i]valueForKey:@”firstName”]);

        }

        

    }

}

– (IBAction)buttonActionDeleteAllData:(id)sender {

    

    [CoreDataUtility deleteAllRecords];

}

@end

CoreDataManager.h

#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>

@interface CoreDataManager : NSObject

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

+ (CoreDataManager *)sharedCoreDataManager;

– (void)saveContext;

– (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data

@end

CoreDataManager.m

#import “CoreDataManager.h”

@implementation CoreDataManager

@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

+ (CoreDataManager *)sharedCoreDataManager

{

    static CoreDataManager *sharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[CoreDataManager alloc]init];

    });

    return sharedInstance;

}

#pragma mark – Application’s Documents directory

// Returns the URL to the application’s Documents directory.

– (NSURL *)applicationDocumentsDirectory{

    // The directory the application uses to store the Core Data store file. This code uses a directory named “Apple.coreDataApple” in the application’s documents directory.

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

// Returns the managed object model for the application.

// If the model doesn’t already exist, it is created from the application’s model.

– (NSManagedObjectModel *)managedObjectModel

{

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”CoreDataModel” withExtension:@”momd”];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

/*

// Returns the persistent store coordinator for the application.

// If the coordinator doesn’t already exist, it is created and the application’s store added to it.

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

if (_persistentStoreCoordinator != nil) {

return _persistentStoreCoordinator;

}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreDataModel.sqlite”];

NSError *error = nil;

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

//         Replace this implementation with code to handle the error appropriately.

//

//         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

//

//         Typical reasons for an error here include:

//         * The persistent store is not accessible;

//         * The schema for the persistent store is incompatible with current managed object model.

//         Check the error message to determine what the actual problem was.

//

//         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application’s resources directory instead of a writeable directory.

//

//         If you encounter schema incompatibility errors during development, you can reduce their frequency by:

//         * Simply deleting the existing store:

//         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

//

//         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:

//         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

//

//         Lightweight migration will only work for a limited set of schema changes; consult “Core Data Model Versioning and Data Migration Programming Guide” for details.

NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

abort();

}

return _persistentStoreCoordinator;

}

*/

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    

    // Create the coordinator and store

    

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreDataModel.sqlite”];

    NSError *error = nil;

    NSString *failureReason = @”There was an error creating or loading the application’s saved data.”;

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        dict[NSLocalizedDescriptionKey] = @”Failed to initialize the application’s saved data”;

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSError errorWithDomain:@”YOUR_ERROR_DOMAIN” code:9999 userInfo:dict];

        // Replace this with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

        abort();

    }

    

    return _persistentStoreCoordinator;

}

// Returns the managed object context for the application.

// If the context doesn’t already exist, it is created and bound to the persistent store coordinator for the application.

– (NSManagedObjectContext *)managedObjectContext

{

    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (!coordinator)

    {

        return nil;

    }

    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    

    return _managedObjectContext;

}

#pragma mark – Core Data Saving support

– (void)saveContext{

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        NSError *error = nil;

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

            abort();

        }

    }

}

@end

CoreDataUtility.h

#import <Foundation/Foundation.h>

#import “CoreDataManager.h”

#import “Form.h”

@interface CoreDataUtility : NSObject

+ (void)insertData:(id)aData;

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo;

+ (void)updateData:(id)aData;

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo;

+ (NSArray *)getAllRecords;

+ (void)deleteAllRecords;

@end

CoreDataUtility.m

#import “CoreDataUtility.h”

@implementation CoreDataUtility

+ (void)insertData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    

    Form *aForm = (Form *)[NSEntityDescription insertNewObjectForEntityForName:@”Form” inManagedObjectContext:[[CoreDataManager sharedCoreDataManager]managedObjectContext]];

    

    aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

    aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

    aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

    aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

    aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    

    

    NSError *error = nil;

    [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

    

}

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo

{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@”Form” inManagedObjectContext:[[CoreDataManager sharedCoreDataManager]managedObjectContext]];

    [fetchRequest setEntity:entity];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@”rollNo == %@”, aRollNo];

    [fetchRequest setPredicate:predicate];

    

    NSError *error = nil;

    

    NSArray *fetchResults = [[[CoreDataManager sharedCoreDataManager]managedObjectContext] executeFetchRequest:fetchRequest error:&error];

    

    Form *aForm = [fetchResults lastObject];

    return aForm;

    

}

+ (void)updateData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    

    NSString *rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    Form *aForm = [self getStudentDetailRollNo:rollNo];

    

    if (aForm != nil)

    {

        aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

        aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

        aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

        aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

        aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

        

        NSError *error = nil;

        [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

        

    }

    else

    {

        NSLog(@”Record Not Found”);

    }

    

}

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo

{

    

    Form *aForm = [self getStudentDetailRollNo:aRollNo];

    

    if (aForm != nil)

    {

        [[[CoreDataManager sharedCoreDataManager]managedObjectContext] deleteObject:aForm];

    }

    NSError *error = nil;

    [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

}

+ (NSArray *)getAllRecords

{

    

    

    NSManagedObjectContext *context =[[CoreDataManager sharedCoreDataManager]managedObjectContext];

    

    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@”Form”];

    

    NSError *error = nil;

    NSArray *arrayresults = [context executeFetchRequest:request error:&error];

    

    for (NSManagedObject *obj in arrayresults)

    {

        NSArray *keys = [[[obj entity] attributesByName] allKeys];

        NSArray *values = [[[obj entity] attributesByName] allValues];

        

        NSLog(@”%@”,keys);

        NSLog(@”%@”,values);

        

    }

    

    return arrayresults;

}

+ (void)deleteAllRecords;

{

    

    NSPersistentStore *store = [[[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] persistentStores] lastObject];

    NSError *error = nil;

    NSURL *storeURL = store.URL;

    [[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] removePersistentStore:store error:&error];

    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

    

    //Make new persistent store for future saves   (Taken From Above Answer)

    if (![[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

    {

        // do something with the error

        NSLog(@”%@”,error);

    }

    else

    {

        NSLog(@”Data Reset”);

    }

    

}

@end

Download Sample Project From Github

Convert Object To NSString

– (NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”\n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

Convert Dictionay To String For GET API

NSDictionary+UrlEncoding.h

#import <Foundation/Foundation.h>

@interface NSDictionary (UrlEncoding)

– (NSString *)urlEncodedString;

@end

NSDictionary+UrlEncoding.m

#import “NSDictionary+UrlEncoding.h”

// helper function: get the string form of any object

static NSString *toString(id object) {

    return [NSString stringWithFormat: @”%@”, object];

}

// helper function: get the url encoded string form of any object

static NSString *urlEncode(id object) {

    NSString *string = toString(object);

    NSCharacterSet *characterSet = [NSCharacterSet URLHostAllowedCharacterSet];

    return [string stringByAddingPercentEncodingWithAllowedCharacters:characterSet];

  //  return [string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

}

@implementation NSDictionary (UrlEncoding)

-(NSString*) urlEncodedString {

    NSMutableArray *parts = [NSMutableArray array];

    for (id key in self) {

        id value = [self objectForKey: key];

        NSString *part = [NSString stringWithFormat: @”%@=%@”, urlEncode(key), urlEncode(value)];

        [parts addObject: part];

    }

    return [parts componentsJoinedByString: @”&”];

}

@end

ViewController.m

#import “NSDictionary+UrlEncoding.h”

– (void)viewDidLoad {

    [super viewDidLoad];

       

    

    NSDictionary *dictionaryNew = @{@”key”: @”28c15c0b405c1f7a107133edf5504367″,

                                    @”name”: @”Rohan Kadam”,

                                    @”mobile_no”: @”9111111111,

                                    @”email_id”: @”rohank989@gmail.com”,

                                    @”password”: @”1234″,

                                    @”mode”: @”R”,};

    

    NSLog(@”%@”,dictionaryNew);

    NSLog(@”%@”,[dictionaryNew urlEncodedString]);

    

    

    NSString *stringURLForGetResponce = [NSString stringWithFormat:@”%@%@”,@”http://yourapi/webservices/userRegistration?&#8221;,[dictionaryNew urlEncodedString]];

    NSLog(@”%@”,stringURLForGetResponce);

    

    // Do any additional setup after loading the view, typically from a nib.

}

Update Multiplier

ViewController.h

#import <UIKit/UIKit.h>

#import “NSLayoutConstraint+Multiplier.h”

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutConstraintViewHeight;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

//    _layoutConstraintViewHeight.constant = 100;

    

    self.layoutConstraintViewHeight = [self.layoutConstraintViewHeight updateMultiplier:0.5];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

NSLayoutConstraint+Multiplier.h

#import <UIKit/UIKit.h>

@interface NSLayoutConstraint (Multiplier)

-(instancetype)updateMultiplier:(CGFloat)multiplier;

@end

NSLayoutConstraint+Multiplier.m

#import “NSLayoutConstraint+Multiplier.h”

@implementation NSLayoutConstraint (Multiplier)

-(instancetype)updateMultiplier:(CGFloat)multiplier {

    NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:self.firstItem attribute:self.firstAttribute relatedBy:self.relation toItem:self.secondItem attribute:self.secondAttribute multiplier:multiplier constant:self.constant];

    [newConstraint setPriority:self.priority];

    newConstraint.shouldBeArchived = self.shouldBeArchived;

    newConstraint.identifier = self.identifier;

    newConstraint.active = true;

    

    [NSLayoutConstraint deactivateConstraints:[NSArray arrayWithObjects:self, nil]];

    [NSLayoutConstraint activateConstraints:[NSArray arrayWithObjects:newConstraint, nil]];

    //NSLayoutConstraint.activateConstraints([newConstraint])

    return newConstraint;

}

@end

Download Sample Project From Github

UitableView Cell Load with animation

//This function is where all the magic happens

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    

    

    //1. Setup the CATransform3D structure

    CATransform3D rotation;

    rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);

    rotation.m34 = 1.0/ –600;

    

    //2. Define the initial state (Before the animation)

    cell.layer.shadowColor = [[UIColor blackColor]CGColor];

    cell.layer.shadowOffset = CGSizeMake(10, 10);

    cell.alpha = 0;

    

    cell.layer.transform = rotation;

    cell.layer.anchorPoint = CGPointMake(0, 0.5);

    

    //!!!FIX for issue #1 Cell position wrong————

    if(cell.layer.position.x != 0){

        cell.layer.position = CGPointMake(0, cell.layer.position.y);

    }

    

    //4. Define the final state (After the animation) and commit the animation

    [UIView beginAnimations:@”rotation” context:NULL];

    [UIView setAnimationDuration:0.8];

    cell.layer.transform = CATransform3DIdentity;

    cell.alpha = 1;

    cell.layer.shadowOffset = CGSizeMake(0, 0);

    [UIView commitAnimations];

}

Singleton Method Sample Project

ViewController.m

#import “SingletonClass.h”

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *stringFirst = @”First”;

    NSString *stringSecond = @”Second”;

    NSString *stringConcatenated;

    stringConcatenated = [[SingletonClass sharedSingletonClass]twoStringConcatenationFirstString:stringFirst SeconString:stringSecond];

    NSLog(@”%@”,stringConcatenated);

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

SingletonClass.h

#import <Foundation/Foundation.h>

@interface SingletonClass : NSObject

+ (SingletonClass *)sharedSingletonClass;

– (NSString *)twoStringConcatenationFirstString:(NSString *)aFirstString SeconString:(NSString *)aSecondString;

@end

SingletonClass.m

#import “SingletonClass.h”

@implementation SingletonClass

+ (SingletonClass *)sharedSingletonClass

{

    static SingletonClass *sharedInstance = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^

                  {

                      sharedInstance = [[self alloc]init];

                  });

    return sharedInstance;

}

– (NSString *)twoStringConcatenationFirstString:(NSString *)aFirstString SeconString:(NSString *)aSecondString

{

    NSString *strinfConcatenation;

    strinfConcatenation = [aFirstString stringByAppendingString:aSecondString];

    return strinfConcatenation;

}

@end

Download Sample Project From Github

Show TableView, ImageView, TextField, View as popup

Referance From :: https://github.com/xiekw2010/DXPopover

PopoverDisplayViewController.m

#import “PopoverDisplayViewController.h”

#import “DXPopover.h”

static CGFloat randomFloatBetweenLowAndHigh(CGFloat low, CGFloat high) {

    CGFloat diff = high – low;

    return (((CGFloat)rand() / RAND_MAX) * diff) + low;

}

@interface PopoverDisplayViewController ()<UITableViewDataSource, UITableViewDelegate> {

    CGFloat _popoverWidth;

    CGSize _popoverArrowSize;

    CGFloat _popoverCornerRadius;

    CGFloat _animationIn;

    CGFloat _animationOut;

    BOOL _animationSpring;

}

@property (nonatomic, strong) UIButton *btn;

@property (nonatomic, strong) UIButton *downBtn;

@property (nonatomic, strong) NSArray *configs;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) DXPopover *popover;

@end

@implementation PopoverDisplayViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    self.tabBarItem.title = @”Configs”;

    self.view.backgroundColor = [UIColor grayColor];

    self.navigationItem.rightBarButtonItem =

    [[UIBarButtonItem alloc] initWithTitle:@”Reset”

                                     style:UIBarButtonItemStylePlain

                                    target:self

                                    action:@selector(resetPopover)];

    UIButton *titleLb = [[UIButton alloc] initWithFrame:(CGRect){CGPointZero, CGSizeMake(100, 40)}];

    [titleLb setTitle:@”Tap Here” forState:UIControlStateNormal];

    [titleLb addTarget:self

                action:@selector(titleShowPopover)

      forControlEvents:UIControlEventTouchUpInside];

    [titleLb setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

    self.navigationItem.titleView = titleLb;

    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];

    [self.btn setTitle:@”Hello” forState:UIControlStateNormal];

    self.btn.frame = CGRectMake(200, 100, 100, 100);

    [self.view addSubview:self.btn];

    [self.btn addTarget:self

                 action:@selector(showPopover)

       forControlEvents:UIControlEventTouchUpInside];

    [self.btn setBackgroundColor:[UIColor cyanColor]];

    self.downBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    [self.downBtn setTitle:@”world” forState:UIControlStateNormal];

    self.downBtn.frame = CGRectMake(10, 400, 100, 100);

    [self.view addSubview:self.downBtn];

    [self.downBtn addTarget:self

                     action:@selector(showPopover1)

           forControlEvents:UIControlEventTouchUpInside];

    [self.downBtn setBackgroundColor:[UIColor purpleColor]];

    UITableView *blueView = [[UITableView alloc] init];

    blueView.frame = CGRectMake(0, 0, _popoverWidth, 350);

    blueView.dataSource = self;

    blueView.delegate = self;

    self.tableView = blueView;

    [self resetPopover];

    self.configs = @[

                     @”changeWidth”,

                     @”ChangeArrowSize”,

                     @”ChangeCornerRadius”,

                     @”changeAnimationIn”,

                     @”changeAnimationOut”,

                     @”changeAnimationSpring”,

                     @”changeMaskType”

                     ];

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (void)resetPopover {

    self.popover = [DXPopover new];

    _popoverWidth = 280.0;

}

– (void)titleShowPopover {

    [self updateTableViewFrame];

    self.popover.contentInset = UIEdgeInsetsMake(20, 5.0, 20, 5.0);

    self.popover.backgroundColor = [UIColor orangeColor];

    UIView *titleView = self.navigationItem.titleView;

    CGPoint startPoint =

    CGPointMake(CGRectGetMidX(titleView.frame), CGRectGetMaxY(titleView.frame) + 20);

    [self.popover showAtPoint:startPoint

               popoverPostion:DXPopoverPositionDown

              withContentView:self.tableView

                       inView:self.tabBarController.view];

    __weak typeof(self) weakSelf = self;

    self.popover.didDismissHandler = ^{

        [weakSelf bounceTargetView:titleView];

    };

}

– (void)showPopover {

    [self updateTableViewFrame];

    CGPoint startPoint =

    CGPointMake(CGRectGetMidX(self.btn.frame), CGRectGetMaxY(self.btn.frame) + 5);

    [self.popover showAtPoint:startPoint

               popoverPostion:DXPopoverPositionDown

              withContentView:self.tableView

                       inView:self.view];

    __weak typeof(self) weakSelf = self;

    self.popover.didDismissHandler = ^{

        [weakSelf bounceTargetView:weakSelf.btn];

    };

}

– (void)showPopover1 {

    [self updateTableViewFrame];

    CGPoint startPoint =

    CGPointMake(CGRectGetMidX(self.downBtn.frame) + 30, CGRectGetMinY(self.downBtn.frame) – 5);

    [self.popover showAtPoint:startPoint

               popoverPostion:DXPopoverPositionUp

              withContentView:self.tableView

                       inView:self.view];

    __weak typeof(self) weakSelf = self;

    self.popover.didDismissHandler = ^{

        [weakSelf bounceTargetView:weakSelf.downBtn];

    };

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.configs.count;

}

– (UITableViewCell *)tableView:(UITableView *)tableView

         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellId = @”cellIdentifier”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault

                                      reuseIdentifier:cellId];

    }

    cell.textLabel.text = self.configs[indexPath.row];

    return cell;

}

static int i = 0;

static int j = 1;

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {

        int c = i % 3;

        if (c == 0) {

            _popoverWidth = 160.0;

        } else if (c == 1) {

            _popoverWidth = 250.0;

        } else if (c == 2) {

            _popoverWidth = 300.0;

        }

        i++;

    } else if (indexPath.row == 1) {

        CGSize arrowSize = self.popover.arrowSize;

        arrowSize.width += randomFloatBetweenLowAndHigh(3.0, 5.0);

        arrowSize.height += randomFloatBetweenLowAndHigh(3.0, 5.0);

        self.popover.arrowSize = arrowSize;

    } else if (indexPath.row == 2) {

        self.popover.cornerRadius += randomFloatBetweenLowAndHigh(0.0, 1.0);

    } else if (indexPath.row == 3) {

        self.popover.animationIn = randomFloatBetweenLowAndHigh(0.4, 2.0);

    } else if (indexPath.row == 4) {

        self.popover.animationOut = randomFloatBetweenLowAndHigh(0.4, 2.0);

    } else if (indexPath.row == 5) {

        self.popover.animationSpring = !self.popover.animationSpring;

    } else if (indexPath.row == 6) {

        self.popover.maskType = j % 2;

        j++;

    }

    [self.popover dismiss];

}

– (void)updateTableViewFrame {

    CGRect tableViewFrame = self.tableView.frame;

    tableViewFrame.size.width = _popoverWidth;

    self.tableView.frame = tableViewFrame;

    self.popover.contentInset = UIEdgeInsetsZero;

    self.popover.backgroundColor = [UIColor whiteColor];

}

– (void)bounceTargetView:(UIView *)targetView {

    targetView.transform = CGAffineTransformMakeScale(0.9, 0.9);

    [UIView animateWithDuration:0.5

                          delay:0.0

         usingSpringWithDamping:0.3

          initialSpringVelocity:5

                        options:UIViewAnimationOptionCurveEaseInOut

                     animations:^{

                         targetView.transform = CGAffineTransformIdentity;

                     }

                     completion:nil];

}

@end

OthersViewViewController.m

#import “OthersViewViewController.h”

#import “DXPopover.h”

@interface OthersViewViewController () {

    CGRect _brownViewOriginRect;

}

@property (weak, nonatomic) IBOutlet UIButton *topLeftBtn;

@property (weak, nonatomic) IBOutlet UIButton *topRightBtn;

@property (weak, nonatomic) IBOutlet UIButton *middleBtn;

@property (weak, nonatomic) IBOutlet UIButton *bottomRightBtn;

@property (weak, nonatomic) IBOutlet UIButton *bottomLeftBtn;

@property (weak, nonatomic) IBOutlet UIButton *middleLeftBtn;

@property (nonatomic, strong) UIView *outsideView;

@property (nonatomic, strong) UIView *innerView;

@end

@implementation OthersViewViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    self.outsideView = [[UIView alloc] initWithFrame:CGRectMake(180, 120, 120, 250)];

    self.outsideView.backgroundColor = [UIColor darkGrayColor];

    [self.view addSubview:self.outsideView];

    _brownViewOriginRect = CGRectMake(10, 10, 100, 100);

    self.innerView = [[UIView alloc] initWithFrame:_brownViewOriginRect];

    self.innerView.backgroundColor = [UIColor brownColor];

    [self.outsideView addSubview:self.innerView];

}

// Show an imageView

– (IBAction)topLeft:(id)sender {

    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];

    imageV.image = [UIImage imageNamed:@”ig12.jpg”];

    DXPopover *popover = [DXPopover popover];

    [popover showAtView:sender withContentView:imageV];

}

// Show an label

– (IBAction)topRight:(id)sender {

    DXPopover *popover = [DXPopover popover];

    popover.backgroundColor = [UIColor purpleColor];

    [popover showAtView:sender

               withText:[[NSAttributedString alloc] initWithString:@”jkjljdalkjdkljalfjklaj”]];

}

// show an seg

– (IBAction)bottomLeft:(id)sender {

    UISegmentedControl *switcher = [[UISegmentedControl alloc] initWithItems:@[ @”You”, @”Me” ]];

    DXPopover *popover = [DXPopover popover];

    [popover showAtView:sender withContentView:switcher inView:self.view];

}

// show an xibfile

– (IBAction)middleLeft:(id)sender {

    //拿出xib视图

    NSArray  *apparray= [[NSBundle mainBundle]loadNibNamed:@”XibFile” owner:nil options:nil];

    UIView *appview=[apparray firstObject];

    

    

    DXPopover *popover = [DXPopover popover];

    [popover showAtView:sender withContentView:appview];

    

}

// Note: Here if you don’t give the position down, then it will show on up, because the atView’s

// distance from containerViews’ top edge is larger than the distance from the containerView’s

// bottom edge.

– (IBAction)middle:(id)sender {

    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 80)];

    textLabel.text = @”I am middle now”;

    textLabel.backgroundColor = [UIColor whiteColor];

    DXPopover *popover = [DXPopover popover];

    [popover showAtView:sender

         popoverPostion:DXPopoverPositionDown

        withContentView:textLabel

                 inView:self.tabBarController.view];

}

// Show a view from other coordinator system’s view, and give it back when popover dismiss

– (IBAction)bottomRight:(id)sender {

    UIView *switcher = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];

    switcher.backgroundColor = [UIColor redColor];

    DXPopover *popover = [DXPopover popover];

    [popover showAtView:sender withContentView:self.innerView inView:self.view];

    popover.didDismissHandler = ^{

        self.innerView.layer.cornerRadius = 0.0;

        self.innerView.frame = _brownViewOriginRect;

        [self.outsideView addSubview:self.innerView];

    };

}

@end

Download Sample Project Fron Github

View Shadow and Border

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

//    [self setRoundCorner_BorderLayer:_viewFirst.layer cornerRadius:8 borderWidth:2 borderColor:[UIColor blueColor] maskToBounds:YES];

//    [self setShoadow_ShadowColorLayer:_viewFirst.layer shadowOffSetCGSizeMake:CGSizeMake(-15, 20) shadowRadius:8 shadowColor:[UIColor grayColor] shadowOpacity:1];

    

//    [self setRoundCorner_BorderLayer:_buttonFirst.layer cornerRadius:8 borderWidth:2 borderColor:[UIColor blueColor] maskToBounds:YES];

    [self setShoadow_ShadowColorLayer:_buttonFirst.layer shadowOffSetCGSizeMake:CGSizeMake(-15, 20) shadowRadius:8 shadowColor:[UIColor grayColor] shadowOpacity:1 maskToBounds:NO];

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (void)setRoundCorner_BorderLayer:(CALayer *)layer cornerRadius:(float)radius borderWidth:(float)borderWidth borderColor:(UIColor *)borderColor maskToBounds:(BOOL)maskToBounds

{

    layer.cornerRadius = radius;

    layer.borderWidth = borderWidth;

    layer.borderColor = borderColor.CGColor;

    layer.masksToBounds = maskToBounds;

    return;

}

– (void)setShoadow_ShadowColorLayer:(CALayer *)layer shadowOffSetCGSizeMake:(CGSize)offSetSize shadowRadius:(float)radius shadowColor:(UIColor *)color shadowOpacity:(float)opacity maskToBounds:(BOOL)maskToBounds

{

    layer.shadowOffset = offSetSize;

    layer.shadowRadius = radius;

    layer.shadowColor = color.CGColor;

    layer.shadowOpacity = opacity;

    layer.masksToBounds = maskToBounds;

    layer.shadowPath = [UIBezierPath bezierPathWithRect:layer.bounds].CGPath;

    return;

}

Download Sample Project From Github

PageView Controller

BGPPlanRegisterViewController.h

#import <UIKit/UIKit.h>

#import “PersonalDetailsViewController.h”

#import “ApplicationDetailsViewController.h”

#import “NominationDetailsViewController.h”

#import “AgreemnetDetailsViewController.h”

#import “PaymentDetailsViewController.h”

#import “BGPPlanRegisterDataModel.h”

@protocol bGPPlanRegisterViewControllerDelegate <NSObject>

– (void)collectDataAndPassDataIFromPersonalDetailsViewControllerToApplicationDetailsViewControllerDictionaryData:(NSDictionary *)dictionaryData;

@end

@interface BGPPlanRegisterViewController : UIViewController <UIPageViewControllerDelegate,UIPageViewControllerDataSource>

@property (nonatomic, assign) int integerViewControllerIndex;

@property (strong, nonatomic) UIPageViewController *pageViewController;

@property (weak, nonatomic) UIPageControl *pageControl;

@property (strong, nonatomic) NSArray *viewControllers;

@property (strong, nonatomic) BGPPlanRegisterDataModel *dataModelBGPPlanRegister;

@property (strong, nonatomic) PersonalDetailsViewController *personalDetailsViewControllerObj;

@property (strong, nonatomic) ApplicationDetailsViewController *applicationDetailsViewControllerObj;

@property (strong, nonatomic) NominationDetailsViewController *nominationDetailsViewControllerObj;

@property (strong, nonatomic) AgreemnetDetailsViewController *agreemnetDetailsViewControllerObj;

@property (strong, nonatomic) PaymentDetailsViewController *paymentDetailsViewControllerObj;

@property (nonatomic, weak) id<bGPPlanRegisterViewControllerDelegate> delegate;

@property (weak, nonatomic) IBOutlet UIView *viewProgressFirst;

@property (weak, nonatomic) IBOutlet UIView *viewProgressSecond;

@property (weak, nonatomic) IBOutlet UIView *viewProgressThird;

@property (weak, nonatomic) IBOutlet UIView *viewProgressFourth;

@property (weak, nonatomic) IBOutlet UIView *viewProgressFifth;

@property (weak, nonatomic) IBOutlet UIView *viewPageContainer;

@property (weak, nonatomic) IBOutlet UILabel *labelDetails;

@property (weak, nonatomic) IBOutlet UIButton *buttonPrevious;

@property (weak, nonatomic) IBOutlet UIButton *buttonNext;

@property (weak, nonatomic) IBOutlet UIButton *buttonSubmit;

– (IBAction)buttonActionPrevious:(id)sender;

– (IBAction)buttonActionNext:(id)sender;

– (IBAction)buttonActionSubmit:(id)sender;

@end

BGPPlanRegisterViewController.m

#import “BGPPlanRegisterViewController.h”

@interface BGPPlanRegisterViewController ()

@end

@implementation BGPPlanRegisterViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    _dataModelBGPPlanRegister = [BGPPlanRegisterDataModel new];

    _dataModelBGPPlanRegister.Auth_Token = @”USA”;

    // Create page view controller

    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll

                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];

    [self.pageViewController.view setFrame:[_viewPageContainer bounds]];

    self.pageViewController.dataSource = self;

    self.pageViewController.delegate = self;

    

    _personalDetailsViewControllerObj = [[UIStoryboard storyboardWithName:@”BGPPlanRegisterStoryboard” bundle:nil]instantiateViewControllerWithIdentifier:@”PersonalDetailsViewController”];

    _personalDetailsViewControllerObj.dataModelBGPPlanRegister = _dataModelBGPPlanRegister;

//    _personalDetailsViewControllerObj.dataModelBGPPlanRegister = (BGPPlanRegisterDataModel *) @{@”Name”: @”BGPPlanRegisterViewController”};

    

    _applicationDetailsViewControllerObj = [[UIStoryboard storyboardWithName:@”BGPPlanRegisterStoryboard” bundle:nil]instantiateViewControllerWithIdentifier:@”ApplicationDetailsViewController”];

    

    _nominationDetailsViewControllerObj = [[UIStoryboard storyboardWithName:@”BGPPlanRegisterStoryboard” bundle:nil]instantiateViewControllerWithIdentifier:@”NominationDetailsViewController”];

    

    _agreemnetDetailsViewControllerObj = [[UIStoryboard storyboardWithName:@”BGPPlanRegisterStoryboard” bundle:nil]instantiateViewControllerWithIdentifier:@”AgreemnetDetailsViewController”];

    

    _paymentDetailsViewControllerObj = [[UIStoryboard storyboardWithName:@”BGPPlanRegisterStoryboard” bundle:nil]instantiateViewControllerWithIdentifier:@”PaymentDetailsViewController”];

    

    

    _viewControllers = [NSArray arrayWithObjects:_personalDetailsViewControllerObj, _applicationDetailsViewControllerObj, _nominationDetailsViewControllerObj, _agreemnetDetailsViewControllerObj, _paymentDetailsViewControllerObj, nil];

    

    

    _integerViewControllerIndex = 0;

    NSArray *tutorialViews = @[[self viewControllerAtIndex:_integerViewControllerIndex]];

    [self.pageViewController setViewControllers:tutorialViews direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

    

    

    

    [self addChildViewController:_pageViewController];

    [self.viewPageContainer addSubview:_pageViewController.view];

    [self.pageViewController didMoveToParentViewController:self];

    

    _buttonPrevious.hidden = YES;

    _buttonSubmit.hidden = YES;

    [self viewProgressHeighlightNumber:0];

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)buttonActionPrevious:(id)sender {

    

    if (_integerViewControllerIndex == 1)

    {

        _buttonPrevious.hidden = YES;

    }

    

    if (_integerViewControllerIndex == 4) {

        _buttonNext.hidden = NO;

        _buttonSubmit.hidden = YES;

    }

    

    if (_integerViewControllerIndex >= 1) {

        

        _integerViewControllerIndex –;

        [self viewProgressHeighlightNumber:_integerViewControllerIndex];

        NSArray *tutorialViews = @[[self viewControllerAtIndex:_integerViewControllerIndex]];

        [self.pageViewController setViewControllers:tutorialViews direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];

        

    }

    

}

– (IBAction)buttonActionNext:(id)sender {

    

    

    if (_integerViewControllerIndex == 0)

    {

        if (![_personalDetailsViewControllerObj shouldGoNextScreen])

        {

            return;

        }

        _buttonPrevious.hidden = NO;

        _dataModelBGPPlanRegister = [_personalDetailsViewControllerObj collectDataInPersonalDetailsViewController];

        _applicationDetailsViewControllerObj.dataModelBGPPlanRegister = _dataModelBGPPlanRegister;

    }

    else if (_integerViewControllerIndex == 1)

    {

        if (![_applicationDetailsViewControllerObj shouldGoNextScreen])

        {

            return;

        }

        _dataModelBGPPlanRegister = [_applicationDetailsViewControllerObj collectDataInApplicationDetailsViewController];

        _nominationDetailsViewControllerObj.dataModelBGPPlanRegister =  _dataModelBGPPlanRegister;

    }

    else if (_integerViewControllerIndex == 2)

    {

        if (![_nominationDetailsViewControllerObj shouldGoNextScreen])

        {

            return;

        }

        _dataModelBGPPlanRegister = [_nominationDetailsViewControllerObj collectDataInNominationDetailsViewController];

        _agreemnetDetailsViewControllerObj.dataModelBGPPlanRegister = _dataModelBGPPlanRegister;

    }

    else if (_integerViewControllerIndex == 3)

    {

        if (![_agreemnetDetailsViewControllerObj shouldGoNextScreen])

        {

            return;

        }

        _dataModelBGPPlanRegister = [_agreemnetDetailsViewControllerObj collectDataInAgreemnetDetailsViewController];

        _paymentDetailsViewControllerObj.dataModelBGPPlanRegister = _dataModelBGPPlanRegister;

        _buttonSubmit.hidden = NO;

        _buttonNext.hidden = YES;

        

    }

    else if (_integerViewControllerIndex == 4)

    {

        if (![_paymentDetailsViewControllerObj shouldGoNextScreen])

        {

            return;

        }

        _dataModelBGPPlanRegister = [_paymentDetailsViewControllerObj collectDataInPaymentDetailsViewController];

        NSLog(@”%@”,[Utility descriptionForObject:_dataModelBGPPlanRegister]);

        

    }

    

    

    

    

    if (_integerViewControllerIndex <= 3) {

        

        _integerViewControllerIndex ++;

        [self viewProgressHeighlightNumber:_integerViewControllerIndex];

        NSArray *viewControllersView = @[[self viewControllerAtIndex:_integerViewControllerIndex]];

        [self.pageViewController setViewControllers:viewControllersView direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

    }

    

}

– (IBAction)buttonActionSubmit:(id)sender {

}

– (UIViewController *)viewControllerAtIndex:(NSUInteger)index

{

    // Create a new view controller and pass suitable data.

    

    UIViewController *viewController = nil;

    if (index == 0)

    {

        viewController = _personalDetailsViewControllerObj;

        _labelDetails.text = @”Personal Details”;

    }

    else if (index == 1)

    {

        viewController = _applicationDetailsViewControllerObj;

        _labelDetails.text = @”Application Details”;

    }

    else if (index == 2)

    {

        viewController = _nominationDetailsViewControllerObj;

        _labelDetails.text = @”Nomination Details”;

    }

    else if (index == 3)

    {

        viewController = _agreemnetDetailsViewControllerObj;

        _labelDetails.text = @”Agreement Details”;

    }

    else if (index == 4)

    {

        viewController = _paymentDetailsViewControllerObj;

        _labelDetails.text = @”Payment Details”;

    }

    

    return viewController;

}

#pragma mark – Page View Controller Data Source

//- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{

//

//    if ([viewController isKindOfClass:[PersonalDetailsViewController class]]) {

//        return  [self viewControllerAtIndex:1];

//    }

//    else if ([viewController isKindOfClass:[ApplicationDetailsViewController class]])

//    {

//        return [self viewControllerAtIndex:2];

//    }

//    else

//    {

//        return nil;

//    }

//

//}

//

//- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{

//

//    if ([viewController isKindOfClass:[NominationDetailsViewController class]]) {

//        return  [self viewControllerAtIndex:2];

//    }

//    else if ([viewController isKindOfClass:[ApplicationDetailsViewController class]]){

//        return [self viewControllerAtIndex:1];

//    }

//    else{

//        return nil;

//    }

//

//}

– (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController

{

    //    For show Page Indicator

    //    return [self.pageTitles count];

    //    return 3;

    return 0;

}

– (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController

{

    return 0;

}

// called before the transition starts

– (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers

{

    NSLog(@”willTransitionToViewControllers”);

}

// called after the transition is finished

– (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed

{

    NSLog(@”transitionCompleted”);

}

– (void)collectDataInApplicationDetailsViewControllerDictionaryData:(NSDictionary *)dictionaryData

{

    NSLog(@”%@”,dictionaryData);

}

– (void)viewProgressHeighlightNumber:(int)viewNumber

{

    NSLog(@”%d”,viewNumber);

    if (viewNumber == 0) {

        _viewProgressFirst.backgroundColor = [UIColor colorWithRed:251/255.0 green:195/255.0 blue:0/255.0 alpha:1];

        _viewProgressSecond.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

        _viewProgressThird.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

        _viewProgressFourth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

        _viewProgressFifth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

    }

    else if (viewNumber == 1)

    {

        _viewProgressFirst.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressSecond.backgroundColor = [UIColor colorWithRed:251/255.0 green:195/255.0 blue:0/255.0 alpha:1];

        _viewProgressThird.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

        _viewProgressFourth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

        _viewProgressFifth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

    }

    else if (viewNumber == 2)

    {

        _viewProgressFirst.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressSecond.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressThird.backgroundColor = [UIColor colorWithRed:251/255.0 green:195/255.0 blue:0/255.0 alpha:1];

        _viewProgressFourth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

        _viewProgressFifth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

    }

    else if (viewNumber == 3)

    {

        _viewProgressFirst.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressSecond.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressThird.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressFourth.backgroundColor = [UIColor colorWithRed:251/255.0 green:195/255.0 blue:0/255.0 alpha:1];

        _viewProgressFifth.backgroundColor = [UIColor colorWithRed:196/255.0 green:196/255.0 blue:196/255.0 alpha:1];

    }

    else if (viewNumber == 4)

    {

        _viewProgressFirst.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressSecond.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressThird.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressFourth.backgroundColor = [UIColor colorWithRed:145/255.0 green:202/255.0 blue:65/255.0 alpha:1];

        _viewProgressFifth.backgroundColor = [UIColor colorWithRed:251/255.0 green:195/255.0 blue:0/255.0 alpha:1];

    }

    

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];// this will do the trick

}

@end

PersonalDetailsViewController.h

#import <UIKit/UIKit.h>

#import “Constant.h”

#import “Utility.h”

#import “BGPPlanRegisterDataModel.h”

@interface PersonalDetailsViewController : UIViewController<UITextFieldDelegate>

@property (strong, nonatomic) BGPPlanRegisterDataModel *dataModelBGPPlanRegister;

@property (strong, nonatomic) UITextField *textFieldActive;

@property (weak, nonatomic) IBOutlet UIButton *buttonMale;

@property (weak, nonatomic) IBOutlet UIButton *buttonFemale;

@property (weak, nonatomic) IBOutlet UITextField *textFieldName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldEmailID;

@property (weak, nonatomic) IBOutlet UITextField *textFieldMobileNumber;

@property (weak, nonatomic) IBOutlet UILabel *labelDate;

@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

@property (weak, nonatomic) IBOutlet UIView *viewDatePicker;

– (BGPPlanRegisterDataModel *)collectDataInPersonalDetailsViewController;

– (BOOL)shouldGoNextScreen;

– (IBAction)buttonActionMale:(id)sender;

– (IBAction)buttonActionFemale:(id)sender;

– (IBAction)buttonActionDate:(id)sender;

– (IBAction)datePickerAction:(id)sender;

@end

PersonalDetailsViewController.m

#import “PersonalDetailsViewController.h”

@interface PersonalDetailsViewController ()

@end

@implementation PersonalDetailsViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    NSLog(@”%@”,[Utility descriptionForObject:_dataModelBGPPlanRegister]);

    

    _buttonMale.selected = YES;

    _labelDate.text = nil;

    _viewDatePicker.hidden = YES;

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self.view addGestureRecognizer:tapGesture];

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (BGPPlanRegisterDataModel *)collectDataInPersonalDetailsViewController

{

    

//    applicant_name;

//    applicant_gender;

//    contact_email;

//    contact_mobile;

//    applicant_dob;

    

    NSString *stringMaleORFemale;

    if (self.buttonMale.selected)

    {

        NSLog(@”Male”);

        stringMaleORFemale = @”Male”;

    }

    

    else if(self.buttonFemale.selected)

    {

        NSLog(@”Female”);

        stringMaleORFemale = @”Female”;

    }

    

    

    _dataModelBGPPlanRegister.applicant_name = _textFieldName.text;

    _dataModelBGPPlanRegister.applicant_gender = stringMaleORFemale;

    _dataModelBGPPlanRegister.contact_email = _textFieldEmailID.text;

    _dataModelBGPPlanRegister.contact_mobile = _textFieldMobileNumber.text;

    _dataModelBGPPlanRegister.applicant_dob = _labelDate.text;

    

    return _dataModelBGPPlanRegister;

}

– (BOOL)shouldGoNextScreen

{

    return [self isValidAllTextfield];

}

– (IBAction)buttonActionMale:(id)sender {

    if (!_buttonMale.selected)

    {

        _buttonMale.selected = !_buttonMale.selected;

    }

    _buttonFemale.selected = NO;

}

– (IBAction)buttonActionFemale:(id)sender {

    if (!_buttonFemale.selected)

    {

        _buttonFemale.selected = !_buttonFemale.selected;

    }

    _buttonMale.selected = NO;

}

– (IBAction)buttonActionDate:(id)sender {

    _viewDatePicker.hidden = NO;

    [_textFieldActive resignFirstResponder];

}

– (IBAction)datePickerAction:(id)sender {

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSString *strDate = [dateFormatter stringFromDate:_datePicker.date];

    _labelDate.text = strDate;

    

    /*

    //MM/DD/YYYY

    NSDate *selectedDate = _datePicker.date;

    NSDate * today = [NSDate date];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat:@”MM/dd/yyy”];

    

    NSString *selectedDateString = [formatter stringFromDate:selectedDate];

    NSString *currentDateString = [formatter stringFromDate:today];

    NSComparisonResult compResult = [today compare:selectedDate];

    if ((compResult != NSOrderedAscending) &&

        (NO == [currentDateString isEqualToString:selectedDateString])) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Invalid Move Date” message:@”Please select a valid Move date” delegate:nil cancelButtonTitle:@”OK” otherButtonTitles:nil];

        [alertView show];

        return;

    }

    */

    

}

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    _viewDatePicker.hidden = YES;

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

}

    

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

{

    // return NO to not change text

    

    if (textField == _textFieldMobileNumber)

    {

        // Prevent crashing undo bug – see note below.

        if(range.length + range.location > textField.text.length)

        {

            return NO;

        }

        NSUInteger newLength = [textField.text length] + [string length] – range.length;

        return newLength <= 10;

    }

    else

    {

        return YES;

    }

    

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (BOOL)isValidAllTextfield

{

    [self.view endEditing:YES];

    

    BOOL isValidate = NO;

    

    if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldName.text].length == 0) {

        [Utility showAlertControllerwithMessage:@”Please Enter Name”];

    }

    else if (![Utility isValidEmail:_textFieldEmailID.text])

    {

        [Utility showAlertControllerwithMessage:@”Please Enter valid Email ID”];

    }

    else if (![Utility isValidPhone:[@”+91″ stringByAppendingString:_textFieldMobileNumber.text]])

    {

        [Utility showAlertControllerwithMessage:@”Please Enter valid Phone Number”];

    }

    else if (_labelDate.text.length == 0)

    {

        [Utility showAlertControllerwithMessage:@”Please Select Date”];

    }

    else if (![Utility isAbow18PlusAgeDateOfBirth:_labelDate.text])

    {

        [Utility showAlertControllerwithMessage:@”You need to be 18+ years”];

    }

    else

    {

        isValidate = YES;

    }

    return isValidate;

}

#pragma mark –

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    _viewDatePicker.hidden = YES;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSString *strDate = [dateFormatter stringFromDate:_datePicker.date];

    _labelDate.text = strDate;

}

@end

ApplicationDetailsViewController.h

#import <UIKit/UIKit.h>

#import “BGPPlanRegisterDataModel.h”

#import “Utility.h”

@interface ApplicationDetailsViewController : UIViewController<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@property (strong, nonatomic) BGPPlanRegisterDataModel *dataModelBGPPlanRegister;

@property (strong, nonatomic) UITextField *textFieldActive;

@property (strong, nonatomic) NSMutableArray *arrayTableViewData;

@property (strong, nonatomic) NSString *stringFulfilment;

@property (strong, nonatomic) NSString *stringLeadSourceOther;

@property (assign, nonatomic) BOOL isReferanceDefault;

@property (assign, nonatomic) BOOL isReferanceOther;

@property (weak, nonatomic) IBOutlet UIButton *buttonDimonsJewellery;

@property (weak, nonatomic) IBOutlet UIButton *buttonGoldJewellery;

@property (weak, nonatomic) IBOutlet UIButton *buttonGoldPendent;

@property (weak, nonatomic) IBOutlet UITextField *textFieldReferalID;

@property (weak, nonatomic) IBOutlet UILabel *labelReferance;

@property (weak, nonatomic) IBOutlet UITextField *textFieldMailingAddress;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;

@property (weak, nonatomic) IBOutlet UITextField *textFieldState;

@property (weak, nonatomic) IBOutlet UITextField *textFieldLandmark;

@property (weak, nonatomic) IBOutlet UITextField *textFieldDistrict;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCountry;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPinCode;

@property (weak, nonatomic) IBOutlet UITextField *textFieldLandLine;

@property (weak, nonatomic) IBOutlet UITextField *textFieldOfficeNumber;

@property (weak, nonatomic) IBOutlet UITextField *textFieldMobileNumber;

@property (weak, nonatomic) IBOutlet UITextField *textFieldEmailID;

@property (weak, nonatomic) IBOutlet UIButton *buttonIAgree;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIView *viewPopUpBelowTable;

@property (weak, nonatomic) IBOutlet UITableView *tableViewPopUp;

@property (weak, nonatomic) IBOutlet UIImageView *imagaeViewDropDown;

@property (weak, nonatomic) IBOutlet UIView *viewMain;

– (BGPPlanRegisterDataModel *)collectDataInApplicationDetailsViewController;

– (BOOL)shouldGoNextScreen;

– (IBAction)buttonActionDimondJewellery:(id)sender;

– (IBAction)buttonActionGoldJewellery:(id)sender;

– (IBAction)buttonActionGoldPendent:(id)sender;

– (IBAction)buttonActionReferance:(id)sender;

– (IBAction)buttonActionIAgree:(id)sender;

@end

ApplicationDetailsViewController.m

#import “ApplicationDetailsViewController.h”

@interface ApplicationDetailsViewController ()

@end

@implementation ApplicationDetailsViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,[Utility descriptionForObject:_dataModelBGPPlanRegister]);

    

    _stringFulfilment = @”Coin”;

    _buttonDimonsJewellery.selected = YES;

    _arrayTableViewData = [[NSMutableArray alloc]initWithObjects:@”Website”,@”Social Media”,@”Mobile App”,@”Newspaper”,@”Friend”,@”Other”, nil];

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [_viewMain addGestureRecognizer:tapGesture];

    

    

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGesture:)];

    [_viewPopUpBelowTable addGestureRecognizer:tapGestureRecognizer];

    

    [_tableViewPopUp.layer setCornerRadius:4.0f];

    [_tableViewPopUp.layer setMasksToBounds:YES];

    _tableViewPopUp.separatorStyle = UITableViewCellSeparatorStyleNone;

    

    _textFieldMobileNumber.text = _dataModelBGPPlanRegister.contact_mobile;

    _textFieldEmailID.text = _dataModelBGPPlanRegister.contact_email;

    

    _isReferanceDefault = YES;

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    _tableViewPopUp.hidden = YES;

    _viewPopUpBelowTable.hidden = YES;

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

// Get the new view controller using [segue destinationViewController].

// Pass the selected object to the new view controller.

}

*/

– (BGPPlanRegisterDataModel *)collectDataInApplicationDetailsViewController

{

    //    fulfilment;

    //    partner_code;

    //    lead_source;

    //    lead_source_other

    //    mailing_address;

    //    mailing_city;

    //    mailing_state;

    //    mailing_landmark;

    //    mailing_district;

    //    mailing_country;

    //    mailing_pincode;

    //    contact_phone_residence;

    //    contact_phone_office;

    

    

    _dataModelBGPPlanRegister.fulfilment = _stringFulfilment;

    _dataModelBGPPlanRegister.partner_code = _textFieldReferalID.text;

    if (_isReferanceDefault)

    {

        _dataModelBGPPlanRegister.lead_source = _labelReferance.text;

    }

    else if (_isReferanceOther)

    {

        _dataModelBGPPlanRegister.lead_source_other = _labelReferance.text;

    }

    

    

    _dataModelBGPPlanRegister.mailing_address = _textFieldMailingAddress.text;

    _dataModelBGPPlanRegister.mailing_city = _textFieldCity.text;

    _dataModelBGPPlanRegister.mailing_state = _textFieldState.text;

    _dataModelBGPPlanRegister.mailing_landmark = _textFieldLandmark.text;

    _dataModelBGPPlanRegister.mailing_district = _textFieldDistrict.text;

    _dataModelBGPPlanRegister.mailing_country = _textFieldCountry.text;

    _dataModelBGPPlanRegister.mailing_pincode = _textFieldPinCode.text;

    _dataModelBGPPlanRegister.contact_phone_residence = _textFieldLandLine.text;

    _dataModelBGPPlanRegister.contact_phone_office = _textFieldOfficeNumber.text;

    

    

    return _dataModelBGPPlanRegister;

}

– (BOOL)shouldGoNextScreen

{

    BOOL canGoNextScreen = NO;

    

    if ([self isValidAllTextfield])

    {

        if (_buttonIAgree.selected)

        {

            canGoNextScreen = YES;

        }

        else

        {

            [Utility showAlertControllerwithMessage:@”Please Tick Agreement Check Box”];

        }

        

    }

    

    

    return canGoNextScreen;

}

– (IBAction)buttonActionDimondJewellery:(id)sender

{

    [self tickMarkOnButtonAtIndex:1];

}

– (IBAction)buttonActionGoldJewellery:(id)sender

{

    [self tickMarkOnButtonAtIndex:2];

}

– (IBAction)buttonActionGoldPendent:(id)sender

{

    [self tickMarkOnButtonAtIndex:3];

}

– (IBAction)buttonActionReferance:(id)sender

{

    _viewPopUpBelowTable.hidden = NO;

    _tableViewPopUp.hidden = NO;

    

//    _tableViewPopUp.frame = CGRectMake(_labelReferance.frame.origin.x, _labelReferance.frame.origin.y, _labelReferance.frame.size.width – _imagaeViewDropDown.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    

    _tableViewPopUp.frame = CGRectMake(_tableViewPopUp.frame.origin.x, _tableViewPopUp.frame.origin.y, _tableViewPopUp.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    

}

– (IBAction)buttonActionIAgree:(id)sender

{

    _buttonIAgree.selected = !_buttonIAgree.selected;

}

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    

    //    if (_textFieldActive != _textFieldReferalID && _textFieldActive != _textFieldMailingAddress) {

    //        //    iPhone = -210

    //        //    iPad = -230

    //        [self viewUpDownWithAnimationYCoordinate:-230];

    //    }

    

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

    

}

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

{

    // return NO to not change text

    

    if (textField == _textFieldPinCode)

    {

        // Prevent crashing undo bug – see note below.

        if(range.length + range.location > textField.text.length)

        {

            return NO;

        }

        NSUInteger newLength = [textField.text length] + [string length] – range.length;

        return newLength <= 6;

    }

    else

    {

        return YES;

    }

    

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (BOOL)isValidAllTextfield

{

    [self.view endEditing:YES];

    

    BOOL isValidate = NO;

    

    if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldCity.text].length == 0) {

        [Utility showAlertControllerwithMessage:@”Please Enter City Name”];

    }

    else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldState.text].length == 0) {

        [Utility showAlertControllerwithMessage:@”Please Enter State Name”];

    }

    else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldDistrict.text].length == 0) {

        [Utility showAlertControllerwithMessage:@”Please Enter District Name”];

    }

    else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldPinCode.text].length == 0) {

        [Utility showAlertControllerwithMessage:@”Please Enter Pincode”];

    }

    else

    {

        isValidate = YES;

    }

    return isValidate;

}

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    

}

– (void)tickMarkOnButtonAtIndex:(int)selectedButton

{

    _buttonDimonsJewellery.selected = NO;

    _buttonGoldJewellery.selected = NO;

    _buttonGoldPendent.selected = NO;

    

    if (selectedButton == 1)

    {

        _buttonDimonsJewellery.selected = YES;

        _stringFulfilment = @”Coin”;

    }

    else if (selectedButton == 2)

    {

        _buttonGoldJewellery.selected = YES;

        _stringFulfilment = @”Jewellery”;

    }

    else if (selectedButton == 3)

    {

        _buttonGoldPendent.selected = YES;

        _stringFulfilment = @”Pendant”;

    }

    

}

#pragma mark – View Popup

#pragma mark – TableView Delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [_arrayTableViewData count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”cellTableView”];

    

    cell.textLabel.text = [_arrayTableViewData objectAtIndex:indexPath.row];

    cell.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;

}

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

{

//    view.tintColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1];

}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    return @””;

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 0.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return HT/15.0;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (indexPath.row == [_arrayTableViewData count]-1)

    {

        NSLog(@”Other Selected”);

        _viewPopUpBelowTable.hidden = YES;

        _tableViewPopUp.hidden = YES;

        _isReferanceDefault = NO;

        _isReferanceOther = YES;

        

        

        UIAlertView *alertView = [[UIAlertView alloc]

                                  initWithTitle:nil

                                  message:@”Enter Other Referance”

                                  delegate:self

                                  cancelButtonTitle:nil

                                  otherButtonTitles:@”OK”, nil];

        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;

        [alertView show];

        

//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@”Enter Referance”

//                                                                       message:nil

//                                                                preferredStyle:UIAlertControllerStyleAlert];

//        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

//            // optionally configure the text field

//            textField.keyboardType = UIKeyboardTypeDefault;

//        }];

//        

//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@”OK”

//                                                           style:UIAlertActionStyleDefault

//                                                         handler:^(UIAlertAction *action) {

//                                                             UITextField *textFieldEnterOtherReferance = [alertController.textFields firstObject];

//                                                             NSLog(@”%@”,textFieldEnterOtherReferance.text);

//                                                             if ([Utility trimString_RemoveWhiteSpaceFromString:textFieldEnterOtherReferance.text].length != 0)

//                                                             {

//                                                                 _labelReferance.text = textFieldEnterOtherReferance.text;

//                                                             }

//                                                         }];

//        [alertController addAction:okAction];

//        [self presentViewController:alertController animated:YES completion:nil];

        

    }

    else

    {

        _labelReferance.text = [_arrayTableViewData objectAtIndex:indexPath.row];

        _viewPopUpBelowTable.hidden = YES;

        _tableViewPopUp.hidden = YES;

        _isReferanceDefault = YES;

        _isReferanceOther = NO;

    }

    

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    NSLog(@”%@”,[alertView textFieldAtIndex:0].text);

    _labelReferance.text = [alertView textFieldAtIndex:0].text;

}

-(void)handleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer

{

    _viewPopUpBelowTable.hidden = YES;

    _tableViewPopUp.hidden = YES;

    

}

@end

NominationDetailsViewController.h

#import <UIKit/UIKit.h>

#import “BGPPlanRegisterDataModel.h”

#import “Utility.h”

@interface NominationDetailsViewController : UIViewController<UITextFieldDelegate>

@property (strong, nonatomic) BGPPlanRegisterDataModel *dataModelBGPPlanRegister;

@property (strong, nonatomic) UITextField *textFieldActive;

@property (weak, nonatomic) IBOutlet UITextField *textFieldName;

@property (weak, nonatomic) IBOutlet UILabel *labelDate;

@property (weak, nonatomic) IBOutlet UITextField *textFieldRelationshipWithApplicant;

@property (weak, nonatomic) IBOutlet UIButton *buttonAddressSame;

@property (weak, nonatomic) IBOutlet UITextField *textFieldAddress;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;

@property (weak, nonatomic) IBOutlet UITextField *textFieldState;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPincode;

@property (weak, nonatomic) IBOutlet UIView *viewDatePicker;

@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

– (BGPPlanRegisterDataModel *)collectDataInNominationDetailsViewController;

– (BOOL)shouldGoNextScreen;

– (IBAction)buttonActionDate:(id)sender;

– (IBAction)buttonActionAddressSame:(id)sender;

– (IBAction)datePickerAction:(id)sender;

@end

NominationDetailsViewController.m

#import “NominationDetailsViewController.h”

@interface NominationDetailsViewController ()

@end

@implementation NominationDetailsViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,[Utility descriptionForObject:_dataModelBGPPlanRegister]);

    

    _viewDatePicker.hidden = YES;

    _labelDate.text = nil;

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self.view addGestureRecognizer:tapGesture];

    

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (BGPPlanRegisterDataModel *)collectDataInNominationDetailsViewController

{

//    nomination_name;

//    nomination_dob;

//    nomination_applicant_realtion;

//    nomination_address;

//    nomination_city;

//    nomination_state;

//    nomination_pincode;

    

    _dataModelBGPPlanRegister.nomination_name = _textFieldName.text;

    _dataModelBGPPlanRegister.nomination_dob = _labelDate.text;

    _dataModelBGPPlanRegister.nomination_applicant_realtion = _textFieldRelationshipWithApplicant.text;

    _dataModelBGPPlanRegister.nomination_address = _textFieldAddress.text;

    _dataModelBGPPlanRegister.nomination_city = _textFieldCity.text;

    _dataModelBGPPlanRegister.nomination_state = _textFieldState.text;

    _dataModelBGPPlanRegister.nomination_pincode = _textFieldPincode.text;

    

    return _dataModelBGPPlanRegister;

}

– (BOOL)shouldGoNextScreen

{

    return [self isValidAllTextfield];

}

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing_dataModelBGPPlanRegister.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    _viewDatePicker.hidden = YES;

    

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

}

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

{

    // return NO to not change text

    

    if (textField == _textFieldPincode)

    {

        // Prevent crashing undo bug – see note below.

        if(range.length + range.location > textField.text.length)

        {

            return NO;

        }

        NSUInteger newLength = [textField.text length] + [string length] – range.length;

        return newLength <= 6;

    }

    else

    {

        return YES;

    }

    

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (BOOL)isValidAllTextfield

{

    [self.view endEditing:YES];

    

//    BOOL isValidate = NO;

//    

//    if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldName.text].length == 0) {

//        [Utility showAlertControllerwithMessage:@”Please Enter Name”];

//    }

//    else if (![Utility isValidEmail:_textFieldEmailID.text])

//    {

//        [Utility showAlertControllerwithMessage:@”Please Enter valid Email ID”];

//    }

//    else if (![Utility isValidPhone:[@”+91″ stringByAppendingString:_textFieldMobileNumber.text]])

//    {

//        [Utility showAlertControllerwithMessage:@”Please Enter valid Phone Number”];

//    }

//    else if (_labelDate.text.length == 0)

//    {

//        [Utility showAlertControllerwithMessage:@”Please Select Date”];

//    }

//    else

//    {

//        isValidate = YES;

//    }

    return YES;

}

#pragma mark –

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    _viewDatePicker.hidden = YES;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSString *strDate = [dateFormatter stringFromDate:_datePicker.date];

    _labelDate.text = strDate;

}

– (IBAction)buttonActionDate:(id)sender {

    _viewDatePicker.hidden = NO;

    [_textFieldActive resignFirstResponder];

}

– (IBAction)buttonActionAddressSame:(id)sender

{

    _buttonAddressSame.selected = !_buttonAddressSame.selected;

    

    if (_buttonAddressSame.selected)

    {

        _textFieldAddress.enabled = NO;

        _textFieldCity.enabled = NO;

        _textFieldState.enabled = NO;

        _textFieldPincode.enabled = NO;

        

        _textFieldAddress.text = _dataModelBGPPlanRegister.mailing_address;

        _textFieldCity.text = _dataModelBGPPlanRegister.mailing_city;

        _textFieldState.text = _dataModelBGPPlanRegister.mailing_state;

        _textFieldPincode.text = _dataModelBGPPlanRegister.mailing_pincode;

        

        

    }

    else

    {

        _textFieldAddress.enabled = YES;

        _textFieldCity.enabled = YES;

        _textFieldState.enabled = YES;

        _textFieldPincode.enabled = YES;

        

        _textFieldAddress.text = @””;

        _textFieldCity.text = @””;

        _textFieldState.text = @””;

        _textFieldPincode.text = @””;

        

    }

    

}

– (IBAction)datePickerAction:(id)sender {

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSString *strDate = [dateFormatter stringFromDate:_datePicker.date];

    _labelDate.text = strDate;

}

@end

AgreemnetDetailsViewController.h

#import <UIKit/UIKit.h>

#import “BGPPlanRegisterDataModel.h”

#import “Utility.h”

@interface AgreemnetDetailsViewController : UIViewController

@property (strong, nonatomic) BGPPlanRegisterDataModel *dataModelBGPPlanRegister;

@property (strong, nonatomic) UITextField *textFieldActive;

@property (weak, nonatomic) IBOutlet UIButton *buttonAcceptTC;

@property (weak, nonatomic) IBOutlet UITextField *textFieldDate;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPlace;

@property (weak, nonatomic) IBOutlet UIView *viewAcceptTC;

@property (weak, nonatomic) IBOutlet UIView *viewIProposeTo;

@property (weak, nonatomic) IBOutlet UIView *viewDate;

@property (weak, nonatomic) IBOutlet UIButton *buttonShowTC;

@property (weak, nonatomic) IBOutlet UIView *viewMain;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutConstraintsViewDateTop999;

– (BGPPlanRegisterDataModel *)collectDataInAgreemnetDetailsViewController;

– (BOOL)shouldGoNextScreen;

– (IBAction)buttonActionAcceptTC:(id)sender;

– (IBAction)buttonActionShowTC:(id)sender;

@end

AgreemnetDetailsViewController.m

#import “AgreemnetDetailsViewController.h”

@interface AgreemnetDetailsViewController ()

@end

@implementation AgreemnetDetailsViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,[Utility descriptionForObject:_dataModelBGPPlanRegister]);

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self.view addGestureRecognizer:tapGesture];

    

    _viewIProposeTo.hidden = YES;

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (BGPPlanRegisterDataModel *)collectDataInAgreemnetDetailsViewController

{

//    declaration_date;

//    declaration_place;

    

    _dataModelBGPPlanRegister.declaration_date = _textFieldDate.text;

    _dataModelBGPPlanRegister.declaration_place = _textFieldPlace.text;

    

    return _dataModelBGPPlanRegister;

}

– (BOOL)shouldGoNextScreen

{

    BOOL canGoNextScreen = NO;

    

    if ([self isValidAllTextfield])

    {

        if (_buttonAcceptTC.selected)

        {

            canGoNextScreen = YES;

        }

        else

        {

            [Utility showAlertControllerwithMessage:@”Kindly accept the agreement”];

        }

        

    }

    

    

    return canGoNextScreen;

}

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

}

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

{

    // return NO to not change text

    return YES;

    

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (BOOL)isValidAllTextfield

{

    [self.view endEditing:YES];

    BOOL isValidate = NO;

    

    if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldPlace.text].length == 0) {

        [Utility showAlertControllerwithMessage:@”Please Enter Place”];

    }

    else

    {

        isValidate = YES;

    }

    return isValidate;

}

#pragma mark –

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    

}

– (IBAction)buttonActionAcceptTC:(id)sender

{

    _buttonAcceptTC.selected = !_buttonAcceptTC.selected;

}

– (IBAction)buttonActionShowTC:(id)sender

{

    _buttonShowTC.selected = !_buttonShowTC.selected;

    if (_buttonShowTC.selected)

    {

        _layoutConstraintsViewDateTop999.priority = 748;

        _viewIProposeTo.hidden = NO;

    }

    else

    {

        _layoutConstraintsViewDateTop999.priority = 999;

        _viewIProposeTo.hidden = YES;

    }

   

}

@end

PaymentDetailsViewController.h

#import <UIKit/UIKit.h>

#import “BGPPlanRegisterDataModel.h”

#import “Utility.h”

@interface PaymentDetailsViewController : UIViewController<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) BGPPlanRegisterDataModel *dataModelBGPPlanRegister;

@property (strong, nonatomic) UITextField *textFieldActive;

@property int intPlanSizeRs;

@property int intPlanSizeCount;

@property (strong, nonatomic) NSMutableArray *arrayTableViewData;

@property (strong, nonatomic) NSMutableArray *arrayPaymentMode;

@property (strong, nonatomic) NSMutableArray *arrayChequePickupAMPM;

@property (assign, nonatomic) BOOL isOnline;

@property (assign, nonatomic) BOOL isChequePickUp;

@property (assign, nonatomic) BOOL isChequeSendThroughCourier;

@property (assign, nonatomic) BOOL isCashPickUp;

@property (assign, nonatomic) BOOL isNEFTRTGS;

@property (assign, nonatomic) BOOL isDatePickerChequePickupChequeDate;

@property (assign, nonatomic) BOOL isDatePickerChequePickupPickupDate;

@property (assign, nonatomic) BOOL isDatePickerChequeSendThroughCourierChequeDate;

@property (assign, nonatomic) BOOL isDatePickupCashPickupPickupDate;

@property (assign, nonatomic) BOOL istableViewPaymentMode;

@property (assign, nonatomic) BOOL istableViewChequePickupAMtoPM;

@property (assign, nonatomic) BOOL istableViewCashPickupAMtoPM;

@property (weak, nonatomic) IBOutlet UIButton *buttonMinus;

@property (weak, nonatomic) IBOutlet UIButton *buttonPlus;

@property (weak, nonatomic) IBOutlet UILabel *labelPlanSize;

@property (weak, nonatomic) IBOutlet UIView *viewPANNo;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPANNo;

@property (weak, nonatomic) IBOutlet UIView *viewPaymentMode;

@property (weak, nonatomic) IBOutlet UIView *viewChequePickup;

@property (weak, nonatomic) IBOutlet UIView *viewChequeSendThroughCourier;

@property (weak, nonatomic) IBOutlet UIView *viewCashPickup;

@property (weak, nonatomic) IBOutlet UIView *viewNEFTRTGS;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequePickupChequeNo;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequePickupChequeDate;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequePickupBankName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequePickupAddress;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequePickupContactPerson;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequePickupPickupDate;

@property (weak, nonatomic) IBOutlet UILabel *labelChequePickupAMtoPM;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequeSendChequeNo;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequeSendChequeDate;

@property (weak, nonatomic) IBOutlet UITextField *textFieldChequeSendBankName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCourierAWDNo;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCourierName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCashAddress;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCashContactPerson;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCashPickupDate;

@property (weak, nonatomic) IBOutlet UILabel *labelCashPickupAMtoPM;

@property (weak, nonatomic) IBOutlet UITextField *textFieldNEFTRTGSTransactionID;

@property (weak, nonatomic) IBOutlet UITableView *tableViewPopUp;

@property (weak, nonatomic) IBOutlet UIView *viewPopUpBelowTable;

@property (weak, nonatomic) IBOutlet UILabel *labelPaymentMode;

@property (weak, nonatomic) IBOutlet UIView *viewMain;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIView *viewDatePicker;

@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutConstraintsViewPaymentModeTop999;

– (BGPPlanRegisterDataModel *)collectDataInPaymentDetailsViewController;

– (BOOL)shouldGoNextScreen;

– (IBAction)buttonActionMinus:(id)sender;

– (IBAction)buttonActionPlus:(id)sender;

– (IBAction)buttonActionChequePickpChequeDate:(id)sender;

– (IBAction)buttonActionChequePickupPickupDate:(id)sender;

– (IBAction)buttonActionChequePickupAMtoPM:(id)sender;

– (IBAction)buttonActionCashAMtoPM:(id)sender;

– (IBAction)buttonActionPaymentMode:(id)sender;

– (IBAction)datePickerAction:(id)sender;

– (IBAction)buttonActionChequeSendThroughCourierChequeDate:(id)sender;

– (IBAction)buttonActionCashPickupPickupDate:(id)sender;

@end

PaymentDetailsViewController.m

#import “PaymentDetailsViewController.h”

@interface PaymentDetailsViewController ()

@end

@implementation PaymentDetailsViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    /**************************************************

     **************************************************

     **************************************************

     

     

//   Hit Below API to fetch Payment Method

// http://shagunn.info/cherishws/mobileapi/get_payment_modes

     

     **************************************************

     **************************************************

     **************************************************/

    

    NSLog(@”%@”,[Utility descriptionForObject:_dataModelBGPPlanRegister]);

    

    _arrayPaymentMode = [[NSMutableArray alloc]initWithObjects:@”Online”,@”Cheque Pickup”,@”Cheque send through Courier”,@”Cash Pickup”,@”NEFT/RTGS”, nil];

    _arrayChequePickupAMPM = [[NSMutableArray alloc]initWithObjects:@”10am to 12pm”,@”12pm to 2pm”,@”2pm to 4pm”,@”4pm to 6pm”,@”6pm to 8pm”, nil];

    

    _viewDatePicker.hidden = YES;

    

    _buttonMinus.layer.cornerRadius = 4;

//    _buttonMinus.clipsToBounds = YES;

    _buttonMinus.layer.borderWidth = 2;

    _buttonMinus.layer.borderColor = [UIColor lightGrayColor].CGColor;

    

    

    _buttonPlus.layer.cornerRadius = 4;

    _buttonPlus.layer.borderWidth = 2;

    _buttonPlus.layer.borderColor = [UIColor lightGrayColor].CGColor;

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [_viewMain addGestureRecognizer:tapGesture];

    

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGesture:)];

    [_viewPopUpBelowTable addGestureRecognizer:tapGestureRecognizer];

    

    _intPlanSizeRs = 1000;

    _intPlanSizeCount = 1;

    _labelPlanSize.text = [NSString stringWithFormat:@”%d”,_intPlanSizeRs*_intPlanSizeCount];

    

    [_tableViewPopUp.layer setCornerRadius:4.0f];

    [_tableViewPopUp.layer setMasksToBounds:YES];

    _tableViewPopUp.separatorStyle = UITableViewCellSeparatorStyleNone;

    

    [self showViewAtIndex:0];

    _scrollView.scrollEnabled = NO;

    _isOnline = YES;

    _viewPANNo.hidden = YES;

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    _tableViewPopUp.hidden = YES;

    _viewPopUpBelowTable.hidden = YES;

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (BGPPlanRegisterDataModel *)collectDataInPaymentDetailsViewController

{

//    initial_amount;

//    initial_pay_by;

//    initial_cheque_dd_no;

//    initial_cheque_dd_no_date;

//    initial_bank_name;

//    contact_address;

//    contact_name;

//    pick_date;

//    pick_time;

//    courier_name;

//    courier_tracking;

//    transaction_id;

    

//    _dataModelBGPPlanRegister = [BGPPlanRegisterDataModel new];

    

    _dataModelBGPPlanRegister.initial_amount = _labelPlanSize.text;

    _dataModelBGPPlanRegister.initial_pay_by = _labelPaymentMode.text;

    if (_isOnline)

    {

        

    }

    else if (_isChequePickUp)

    {

        _dataModelBGPPlanRegister.initial_cheque_dd_no = _textFieldChequePickupChequeNo.text;

        _dataModelBGPPlanRegister.initial_cheque_dd_no_date = _textFieldChequePickupChequeDate.text;

        _dataModelBGPPlanRegister.initial_bank_name = _textFieldChequePickupBankName.text;

        _dataModelBGPPlanRegister.contact_address = _textFieldChequePickupAddress.text;

        _dataModelBGPPlanRegister.contact_name = _textFieldChequePickupContactPerson.text;

        _dataModelBGPPlanRegister.pick_date =_textFieldChequePickupPickupDate.text;

        _dataModelBGPPlanRegister.pick_time = _labelChequePickupAMtoPM.text;

        

    }

    else if (_isChequeSendThroughCourier)

    {

        _dataModelBGPPlanRegister.initial_cheque_dd_no = _textFieldChequeSendChequeNo.text;

        _dataModelBGPPlanRegister.initial_cheque_dd_no_date = _textFieldChequeSendChequeDate.text;

        _dataModelBGPPlanRegister.initial_bank_name = _textFieldChequeSendBankName.text;

        _dataModelBGPPlanRegister.courier_name = _textFieldCourierName.text;

        _dataModelBGPPlanRegister.courier_tracking = _textFieldCourierAWDNo.text;

        

    }

    else if (_isCashPickUp)

    {

        _dataModelBGPPlanRegister.contact_address = _textFieldCashAddress.text;

        _dataModelBGPPlanRegister.contact_name = _textFieldCashContactPerson.text;

        _dataModelBGPPlanRegister.pick_date = _textFieldCashPickupDate.text;

        _dataModelBGPPlanRegister.pick_time = _labelCashPickupAMtoPM.text;

    }

    else if (_isNEFTRTGS)

    {

        _dataModelBGPPlanRegister.transaction_id = _textFieldNEFTRTGSTransactionID.text;

    }

    

    

    return _dataModelBGPPlanRegister;

}

– (BOOL)shouldGoNextScreen

{

    return [self isValidAllTextfield];

}

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    _viewDatePicker.hidden = YES;

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

}

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

{

    // return NO to not change text

    return YES;

    

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (BOOL)isValidAllTextfield

{

    [self.view endEditing:YES];

    

    BOOL isValidate = NO;

    

    if (_isOnline)

    {

        isValidate = YES;

    }

    else if (_isChequePickUp)

    {

     

        if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequePickupChequeNo.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cheque No.”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequePickupChequeDate.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please select Cheque Date”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequePickupBankName.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Bank Name”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequePickupAddress.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cheque Pickup Address”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequePickupContactPerson.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cheque Pickup contact Person Name”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequePickupPickupDate.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cheque Pickup Date”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_labelChequePickupAMtoPM.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please Select Cheque pickup Time”];

        }

        else

        {

            isValidate = YES;

        }

        

    }

    else if (_isChequeSendThroughCourier)

    {

        

        if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequeSendChequeNo.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cheque No.”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequeSendChequeDate.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please select Cheque Date”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldChequeSendBankName.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Bank Name”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldCourierAWDNo.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Courier AWD No.”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldCourierName.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Courier Name”];

        }

        else

        {

            isValidate = YES;

        }

        

        

    }

    else if (_isCashPickUp)

    {

        

        if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldCashAddress.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cash Pickup Address”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldCashContactPerson.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cash Pickup contact Person Name”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldCashPickupDate.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please enter Cash Pickup Date”];

        }

        else if ([Utility trimString_RemoveWhiteSpaceFromString:_labelCashPickupAMtoPM.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please Select Cash pickup Time”];

        }

        else

        {

            isValidate = YES;

        }

    }

    else if (_isNEFTRTGS)

    {

        if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldNEFTRTGSTransactionID.text].length == 0)

        {

            [Utility showAlertControllerwithMessage:@”Please Select Transection ID”];

        }

        else

        {

            isValidate = YES;

        }

    }

    

    

    

    

    

    

//    if ([Utility trimString_RemoveWhiteSpaceFromString:_textFieldName.text].length == 0) {

//        [Utility showAlertControllerwithMessage:@”Please Enter Name”];

//    }

//    else if (![Utility isValidEmail:_textFieldEmailID.text])

//    {

//        [Utility showAlertControllerwithMessage:@”Please Enter valid Email ID”];

//    }

//    else if (![Utility isValidPhone:[@”+91″ stringByAppendingString:_textFieldMobileNumber.text]])

//    {

//        [Utility showAlertControllerwithMessage:@”Please Enter valid Phone Number”];

//    }

//    else if (_labelDate.text.length == 0)

//    {

//        [Utility showAlertControllerwithMessage:@”Please Select Date”];

//    }

//    else

//    {

//        isValidate = YES;

//    }

    return isValidate;

}

#pragma mark –

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    _viewDatePicker.hidden = YES;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSString *strDate = [dateFormatter stringFromDate:_datePicker.date];

    

    if (_isDatePickerChequePickupChequeDate)

    {

        _textFieldChequePickupChequeDate.text = strDate;

    }

    else if (_isDatePickerChequePickupPickupDate)

    {

        _textFieldChequePickupPickupDate.text = strDate;

    }

    else if (_isDatePickerChequeSendThroughCourierChequeDate)

    {

        _textFieldChequeSendChequeDate.text = strDate;

    }

    else if (_isDatePickupCashPickupPickupDate)

    {

        _textFieldCashPickupDate.text = strDate;

    }

    

}

– (IBAction)buttonActionMinus:(id)sender

{

    if (_intPlanSizeCount >= 2)

    {

        _intPlanSizeCount –;

    }

    if (_intPlanSizeCount <= 18)

    {

        _layoutConstraintsViewPaymentModeTop999.priority = 999;

        _viewPANNo.hidden = YES;

    }

    _intPlanSizeRs = 1000;

    _labelPlanSize.text = [NSString stringWithFormat:@”%d”,_intPlanSizeRs*_intPlanSizeCount];

    

}

– (IBAction)buttonActionPlus:(id)sender

{

    _intPlanSizeCount ++;

    _intPlanSizeRs = 1000;

    _labelPlanSize.text = [NSString stringWithFormat:@”%d”,_intPlanSizeRs*_intPlanSizeCount];

    if (_intPlanSizeCount == 19)

    {

        NSLog(@”PAN No.”);

        _layoutConstraintsViewPaymentModeTop999.priority = 748;

        _viewPANNo.hidden = NO;

    }

}

– (IBAction)buttonActionChequePickpChequeDate:(id)sender

{

    _viewDatePicker.hidden = NO;

    _isDatePickerChequePickupChequeDate = YES;

    _isDatePickerChequePickupPickupDate = NO;

    _isDatePickerChequeSendThroughCourierChequeDate = NO;

    _isDatePickupCashPickupPickupDate = NO;

    [_textFieldActive resignFirstResponder];

}

– (IBAction)buttonActionChequePickupPickupDate:(id)sender

{

    _viewDatePicker.hidden = NO;

    _isDatePickerChequePickupChequeDate = NO;

    _isDatePickerChequePickupPickupDate = YES;

    _isDatePickerChequeSendThroughCourierChequeDate = NO;

    _isDatePickupCashPickupPickupDate = NO;

    [_textFieldActive resignFirstResponder];

}

– (IBAction)buttonActionChequePickupAMtoPM:(id)sender

{

    _viewPopUpBelowTable.hidden = NO;

    _tableViewPopUp.hidden = NO;

    

    //    _tableViewPopUp.frame = CGRectMake(_labelReferance.frame.origin.x, _labelReferance.frame.origin.y, _labelReferance.frame.size.width – _imagaeViewDropDown.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    

    _arrayTableViewData = _arrayChequePickupAMPM;

    _istableViewPaymentMode = NO;

    _istableViewChequePickupAMtoPM = YES;

    _istableViewCashPickupAMtoPM = NO;

    _tableViewPopUp.frame = CGRectMake(_tableViewPopUp.frame.origin.x, _labelChequePickupAMtoPM.frame.origin.y, _tableViewPopUp.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    [_tableViewPopUp reloadData];

}

– (IBAction)buttonActionCashAMtoPM:(id)sender

{

    _viewPopUpBelowTable.hidden = NO;

    _tableViewPopUp.hidden = NO;

    

    //    _tableViewPopUp.frame = CGRectMake(_labelReferance.frame.origin.x, _labelReferance.frame.origin.y, _labelReferance.frame.size.width – _imagaeViewDropDown.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    

    _arrayTableViewData = _arrayChequePickupAMPM;

    _istableViewPaymentMode = NO;

    _istableViewChequePickupAMtoPM = NO;

    _istableViewCashPickupAMtoPM = YES;

    _tableViewPopUp.frame = CGRectMake(_tableViewPopUp.frame.origin.x, _labelCashPickupAMtoPM.frame.origin.y, _tableViewPopUp.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    [_tableViewPopUp reloadData];

    

}

– (IBAction)buttonActionPaymentMode:(id)sender

{

    _viewPopUpBelowTable.hidden = NO;

    _tableViewPopUp.hidden = NO;

    

    //    _tableViewPopUp.frame = CGRectMake(_labelReferance.frame.origin.x, _labelReferance.frame.origin.y, _labelReferance.frame.size.width – _imagaeViewDropDown.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    

    _arrayTableViewData = _arrayPaymentMode;

    _istableViewPaymentMode = YES;

    _istableViewChequePickupAMtoPM = NO;

    _istableViewCashPickupAMtoPM = NO;

    _tableViewPopUp.frame = CGRectMake(_tableViewPopUp.frame.origin.x, _tableViewPopUp.frame.origin.y, _tableViewPopUp.frame.size.width, (HT/15.0*(_arrayTableViewData.count)));

    [_tableViewPopUp reloadData];

    

}

– (IBAction)datePickerAction:(id)sender

{

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

        [dateFormatter setDateFormat:@”dd/MM/yyyy”];

        NSString *strDate = [dateFormatter stringFromDate:_datePicker.date];

       // _labelDate.text = strDate;

    

    if (_isDatePickerChequePickupChequeDate)

    {

        _textFieldChequePickupChequeDate.text = strDate;

    }

    else if (_isDatePickerChequePickupPickupDate)

    {

        _textFieldChequePickupPickupDate.text = strDate;

    }

    else if (_isDatePickerChequeSendThroughCourierChequeDate)

    {

        _textFieldChequeSendChequeDate.text = strDate;

    }

    else if (_isDatePickupCashPickupPickupDate)

    {

        _textFieldCashPickupDate.text = strDate;

    }

        /*

         //MM/DD/YYYY

         NSDate *selectedDate = _datePicker.date;

         NSDate * today = [NSDate date];

         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

         [formatter setDateFormat:@”MM/dd/yyy”];

         

         NSString *selectedDateString = [formatter stringFromDate:selectedDate];

         NSString *currentDateString = [formatter stringFromDate:today];

         NSComparisonResult compResult = [today compare:selectedDate];

         if ((compResult != NSOrderedAscending) &&

         (NO == [currentDateString isEqualToString:selectedDateString])) {

         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Invalid Move Date” message:@”Please select a valid Move date” delegate:nil cancelButtonTitle:@”OK” otherButtonTitles:nil];

         [alertView show];

         return;

         }

         */

        

    

}

– (IBAction)buttonActionChequeSendThroughCourierChequeDate:(id)sender

{

    _viewDatePicker.hidden = NO;

    _isDatePickerChequePickupChequeDate = NO;

    _isDatePickerChequePickupPickupDate = NO;

    _isDatePickerChequeSendThroughCourierChequeDate = YES;

    _isDatePickupCashPickupPickupDate = NO;

    [_textFieldActive resignFirstResponder];

}

– (IBAction)buttonActionCashPickupPickupDate:(id)sender

{

    _viewDatePicker.hidden = NO;

    _isDatePickerChequePickupChequeDate = NO;

    _isDatePickerChequePickupPickupDate = NO;

    _isDatePickerChequeSendThroughCourierChequeDate = NO;

    _isDatePickupCashPickupPickupDate = YES;

    [_textFieldActive resignFirstResponder];

    

}

#pragma mark – View Popup

#pragma mark – TableView Delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [_arrayTableViewData count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”cellTableView”];

    

    cell.textLabel.text = [_arrayTableViewData objectAtIndex:indexPath.row];

    cell.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    

    return cell;

}

//-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

//{

//    //    view.tintColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1];

//}

//

//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

//{

//    return @””;

//}

//

//

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

//{

//    return 0.0;

//}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return HT/15.0;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    _viewPopUpBelowTable.hidden = YES;

    _tableViewPopUp.hidden = YES;

    

    if (_istableViewPaymentMode)

    {

        _labelPaymentMode.text = [_arrayTableViewData objectAtIndex:indexPath.row];

        

        if (indexPath.row == 0)

        {

            [self showViewAtIndex:0];

            _scrollView.scrollEnabled = NO;

        }

        else if (indexPath.row == 1)

        {

            [self showViewAtIndex:1];

            _scrollView.scrollEnabled = YES;

        }

        else if (indexPath.row == 2)

        {

            [self showViewAtIndex:2];

            _scrollView.scrollEnabled = NO;

        }

        else if (indexPath.row == 3)

        {

            [self showViewAtIndex:3];

            _scrollView.scrollEnabled = NO;

        }

        else if (indexPath.row == 4)

        {

            [self showViewAtIndex:4];

            _scrollView.scrollEnabled = NO;

        }

    }

    else if (_istableViewChequePickupAMtoPM)

    {

        _labelChequePickupAMtoPM.text = [_arrayTableViewData objectAtIndex:indexPath.row];

        

        

    }

    else if (_istableViewCashPickupAMtoPM)

    {

        _labelCashPickupAMtoPM.text = [_arrayTableViewData objectAtIndex:indexPath.row];

        

        

    }

    

}

-(void)handleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer

{

    _viewPopUpBelowTable.hidden = YES;

    _tableViewPopUp.hidden = YES;

    

}

– (void)showViewAtIndex:(int)viewNumber

{

    NSLog(@”%d”,viewNumber);

    _viewChequePickup.hidden = YES;

    _viewChequeSendThroughCourier.hidden = YES;

    _viewCashPickup.hidden = YES;

    _viewNEFTRTGS.hidden = YES;

    

    _isOnline = NO;

    _isChequePickUp = NO;

    _isChequeSendThroughCourier = NO;

    _isCashPickUp = NO;

    _isNEFTRTGS = NO;

    

    switch (viewNumber) {

        case 0:

            _isOnline = YES;

            break;

        case 1:

            _viewChequePickup.hidden = NO;

            _isChequePickUp = YES;

            break;

        case 2:

            _viewChequeSendThroughCourier.hidden = NO;

            _isChequeSendThroughCourier = YES;

            break;

        case 3:

            _viewCashPickup.hidden = NO;

            _isCashPickUp = YES;

            break;

        case 4:

            _viewNEFTRTGS.hidden = NO;

            _isNEFTRTGS = YES;

            break;

            

        default:

            break;

    }

    

}

@end

Download Sample Project From Github

Move View Up when Keyboard appears with IQKeyboardManager

Referance From :: https://github.com/hackiftekhar/IQKeyboardManager.git

#import “IQKeyboardManager.h”

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    

    //Enabling keyboard manager

    [[IQKeyboardManager sharedManager] setEnable:YES];

    

    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:15];

    //Enabling autoToolbar behaviour. If It is set to NO. You have to manually create IQToolbar for keyboard.

    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];

    

    //Setting toolbar behavious to IQAutoToolbarBySubviews. Set it to IQAutoToolbarByTag to manage previous/next according to UITextField’s tag property in increasing order.

    [[IQKeyboardManager sharedManager] setToolbarManageBehaviour:IQAutoToolbarBySubviews];

    

    //Resign textField if touched outside of UITextField/UITextView.

    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];

    

    //Giving permission to modify TextView’s frame

    [[IQKeyboardManager sharedManager] setCanAdjustTextView:YES];

    

    //Show TextField placeholder texts on autoToolbar

    [[IQKeyboardManager sharedManager] setShouldShowTextFieldPlaceholder:YES];

    

    

    return YES;

}

Download Sample Project From Github

HTML Text Show in WebView Clickable

CompanyViewController.h

#import “ViewController.h”

#import “Utility.h”

@interface CompanyViewController : ViewController

@property (strong, nonatomic) NSMutableDictionary *dictionaryJSON;

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

CompanyViewController.m

#import “CompanyViewController.h”

@interface CompanyViewController ()

@end

@implementation CompanyViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    _dictionaryJSON = [[NSMutableDictionary alloc]init];

    _dictionaryJSON = [Utility getValueFromJsonFile_FileName:@”CompanyFile” FileType:@”json”];

    

    NSLog(@”%@”,_dictionaryJSON);

    NSLog(@”%@”,[[_dictionaryJSON objectForKey:@”data”]valueForKeyPath:@”content.static”]);

    

    NSString *string = [[_dictionaryJSON objectForKey:@”data”]valueForKeyPath:@”content.static”];

    NSLog(@”%@”,string);

    

    

    [_webView loadHTMLString:string baseURL:nil];

    

    

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

@end

Download Sample Project From Github

Bridging beetween Swift and Objective C

Swift  and Objective C

Project Targer – Build setting – swift compiler general – Objective c bridging header – ObjectiveCSwiftBrifging/ObjectiveCSwiftBrifging-Bridging-Header.h

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        self.swiftFunction()

        print(self.swiftFunctionWithReturnValue())

        self.swiftFunctionPassingValueToObjectiveCClass()

        self.callOjectiveC()

        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        //Dispose of any resources that can be recreated.

    }

    

    func callOjectiveC()

    {

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        objClass.callASwiftFunction()

    }

    

    func  swiftFunction()

    {

        //Using objective c function here

        print(“Swift Class (__FUNCTION__)”)

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        objClass.objectiveCfunction()

    }

    

    func swiftFunctionWithReturnValue()->String

    {

        var returnValue:String;

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        let objCReturn:String = objClass.objectiveCFunctionWithReturnValue()

        returnValue = “Returning  from swiftFunctionWithReturnValue , appending (objCReturn) “

        return returnValue

    }

    

    func swiftFunctionPassingValueToObjectiveCClass()

    {

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        objClass.objectiveCfunctionWithValuePassedFromSwiftClass(“Passing a string from Swift Class”);

    }

    

    func functionFromObjectiveC()

    {

        print(“In swift class , Function from objective c”);

    }

}

ObjectiveCClass.h

#import <Foundation/Foundation.h>

@interface ObjectiveCClass : NSObject

– (void)objectiveCfunction;

– (NSString *)objectiveCFunctionWithReturnValue;

– (void)objectiveCfunctionWithValuePassedFromSwiftClass:(NSString*)passedValue;

– (void)callASwiftFunction;

@end

ObjectiveCClass.m

#import “ObjectiveCClass.h”

#import “ObjectiveCSwiftBridging-Swift.h”

@implementation ObjectiveCClass

– (void)objectiveCfunction

{

    NSLog(@”Calling %s”,__func__);

}

– (NSString *)objectiveCFunctionWithReturnValue

{

    return @”Returning value from Objective C Class objectiveCFunctionWithReturnValue function”;

}

– (void)objectiveCfunctionWithValuePassedFromSwiftClass:(NSString*)passedValue

{

    NSLog(@”%@ and printed in objective c class %s”,passedValue,__func__);

}

– (void)callASwiftFunction

{

    ViewController *swiftViewcontroller = [[ViewController alloc] init];

    [swiftViewcontroller functionFromObjectiveC];

}

@end

Sample project download from Github

Animated Constraints

ViewController.m

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UISwitch *modeSwitch;

@property (weak, nonatomic) IBOutlet UIView *yellowView;

@property (weak, nonatomic) IBOutlet UIView *blueView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewSpacingContraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *blueViewConstraint;

@end

@implementation ViewController

NSString *modeUserDefaultKey = @”modeUserDefaultKey”;

– (void)viewDidLoad {

    [super viewDidLoad];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    self.modeSwitch.on = [defaults boolForKey:modeUserDefaultKey];

    [self updateConstraintsForMode];

}

– (IBAction)enableMode:(UISwitch *)sender {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setBool:sender.isOn forKey:modeUserDefaultKey];

    [defaults synchronize];

    [self.view layoutIfNeeded];

    [UIView animateWithDuration:1.0 animations:^{

        [self updateConstraintsForMode];

        [self.view layoutIfNeeded];

    }];

}

– (void)updateConstraintsForMode {

    if (self.modeSwitch.isOn) {

        self.viewSpacingContraint.constant = 8.0;

        self.blueViewConstraint.priority = UILayoutPriorityDefaultHigh+1;

    } else {

        self.viewSpacingContraint.constant = self.view.frame.size.width;

        self.blueViewConstraint.priority = UILayoutPriorityDefaultHigh1;

    }

}

@end

UITextView PlaceholderText with Category

UITextView+PlaceholderText.h

#import <UIKit/UIKit.h>

#define DEFAULT_PLACEHOLDER_COLOR (UIColor.lightGrayColor)

#define DRAW_DEBUG 0

@interface UITextView (PlaceholderText)

– (void)setPlaceholder:(NSString *)placeholder;

– (NSString *)placeholder;

– (void)setPlaceholderColor:(UIColor *)placeholderColor;

– (UIColor *)placeholderColor;

– (void)setPlaceholderAnimation:(BOOL)placeholderAnimation;

– (BOOL)placeholderAnimation;

@end

UITextView+PlaceholderText.m

#import “UITextView+PlaceholderText.h”

#import <objc/runtime.h>

#import <objc/message.h>

@implementation UITextView (PlaceholderText)

CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25;

static void * const PLACEHOLDER_KEY = (void*)&PLACEHOLDER_KEY;

static void * const PLACEHOLDER_COLOR_KEY = (void*)&PLACEHOLDER_COLOR_KEY;

static void * const PLACEHOLDER_LABEL_KEY = (void*)&PLACEHOLDER_LABEL_KEY;

static void * const PLACEHOLDER_ANIMATION_KEY = (void*)&PLACEHOLDER_ANIMATION_KEY;

static void

swizzle(Class c, SEL orig, SEL new) {

    Method origMethod = class_getInstanceMethod(c, orig);

    Method newMethod = class_getInstanceMethod(c, new);

    

    if (class_addMethod(c,

                        orig,

                        method_getImplementation(newMethod),

                        method_getTypeEncoding(newMethod)))

    {

        class_replaceMethod(c,

                            new,

                            method_getImplementation(origMethod),

                            method_getTypeEncoding(origMethod));

    } else {

        method_exchangeImplementations(origMethod, newMethod);

    }

}

+ (void)initialize {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        if ([self isKindOfClass:UITextView.class]) {

            swizzle(self, @selector(setText:), @selector(newSetText:));

            swizzle(self, @selector(initWithFrame:), @selector(initWithFrameNew:));

        }

    });

}

– (void)setPlaceholder:(NSString *)placeholder

{

    objc_setAssociatedObject(self,

                             PLACEHOLDER_KEY,

                             placeholder,

                             OBJC_ASSOCIATION_COPY_NONATOMIC);

}

– (void)setup {

#if DRAW_DEBUG

    self.layer.borderColor = UIColor.blueColor.CGColor;

    self.layer.borderWidth = 2;

#endif

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];

}

– (void)awakeFromNib {

    [super awakeFromNib];

    

    [self setup];

}

– (void)textChanged:(NSNotification *)notification

{

    if (self.placeholder.length == 0) {

        return;

    }

    

    if (self.placeholderAnimation) {

        [UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION

                         animations:^{

            [self viewWithTag:999].alpha = (self.text.length == 0) ? 1 : 0;

        }];

    } else {

        [self viewWithTag:999].alpha = (self.text.length == 0) ? 1 : 0;

    }

}

– (id)initWithFrameNew:(CGRect)frame {

    if (self = [self initWithFrameNew:frame]) {

        [self setup];

    }

    return self;

}

– (void)newSetText:(NSString *)text {

    [self newSetText:text];

    [self textChanged:nil];

}

– (NSString *)placeholder

{

    return objc_getAssociatedObject(self, PLACEHOLDER_KEY);

}

– (void)setPlaceholderColor:(UIColor *)placeholderColor

{

    objc_setAssociatedObject(self,

                             PLACEHOLDER_COLOR_KEY,

                             placeholderColor,

                             OBJC_ASSOCIATION_ASSIGN);

}

– (UIColor *)placeholderColor

{

    UIColor *result = objc_getAssociatedObject(self, PLACEHOLDER_KEY);

    if (!!result) {

        result = DEFAULT_PLACEHOLDER_COLOR;

    }

    return result;

}

– (UILabel *)newPlaceholderLabel {

    UILabel *placeholderLabel = [[UILabel alloc] initWithFrame:self.bounds];

    

    placeholderLabel.lineBreakMode = NSLineBreakByClipping;

    placeholderLabel.numberOfLines = 1;

    placeholderLabel.font = self.font;

    placeholderLabel.adjustsFontSizeToFitWidth = YES;

    placeholderLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

    placeholderLabel.backgroundColor = UIColor.clearColor;

    placeholderLabel.textColor = self.placeholderColor;

#if DRAW_DEBUG

    placeholderLabel.layer.borderColor = UIColor.redColor.CGColor;

    placeholderLabel.layer.borderWidth = 4;

#endif

    placeholderLabel.alpha = 0;

    

    placeholderLabel.tag = 999;

    

    [self addSubview:placeholderLabel];

    

    return placeholderLabel;

}

– (void)setPlaceholderLabel:(UILabel *)placeholderLabel {

    objc_setAssociatedObject(self,

                             PLACEHOLDER_LABEL_KEY,

                             placeholderLabel,

                             OBJC_ASSOCIATION_ASSIGN);

}

– (UILabel *)placeholderLabel {

    UILabel *placeholderLabel = objc_getAssociatedObject(self, PLACEHOLDER_LABEL_KEY);

    if (!placeholderLabel) {

        [self setPlaceholderLabel:placeholderLabel = [self newPlaceholderLabel]];

    }

    return placeholderLabel;

}

– (void)setPlaceholderAnimation:(BOOL)placeholderAnimation {

    objc_setAssociatedObject(self,

                             PLACEHOLDER_ANIMATION_KEY,

                             [NSNumber numberWithBool:placeholderAnimation],

                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

– (BOOL)placeholderAnimation {

    return ((NSNumber *)objc_getAssociatedObject(self, PLACEHOLDER_ANIMATION_KEY)).boolValue;

}

– (void)drawRect:(CGRect)rect

{

    if (self.placeholder && self.placeholder.length > 0) {

        self.placeholderLabel.text = self.placeholder;

        [self sendSubviewToBack:self.placeholderLabel];

        if (self.text && self.text.length == 0) {

            [self viewWithTag:999].alpha = 1;

        }

        self.placeholderLabel.textAlignment = self.textAlignment;

    }

    [super drawRect:rect];

}

@end

Sample Project From Github

Get Contact Detail From PhoneBook

#import <Contacts/Contacts.h>

#import <ContactsUI/ContactsUI.h>

<CNContactPickerDelegate>

– (IBAction)buttonActionGetContactDetail:(id)sender {

    CNContactPickerViewController *cNContactPickerViewControllerObject = [[CNContactPickerViewController alloc]init];

    cNContactPickerViewControllerObject.delegate = self;

    [self presentViewController:cNContactPickerViewControllerObject animated:true completion:^{

    }];

}

– (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{

    NSLog(@”%@”,contact);

}

/*

– (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact*> *)contacts{

    NSLog(@”%@”,contacts);

}

*/

Download Sample Project

Hit Api with AFNetworking

APIManagerNew.h

#import <Foundation/Foundation.h>

#import “MBProgressHUD.h”

#import “Utility_ObjectiveC.h”

#import “AFNetworking.h”

#import “ProductDetailAllDataModels.h”

@interface APIManagerNew : NSObject

@property AFHTTPSessionManager *manager;

+ (APIManagerNew *)sharedAPIManager;

– (void)hitAPIuserRegistrationParameters:(NSDictionary *)dictionaryParameters currentView:(UIView *)view completionHandlerSuccess:(void (^)(NSDictionary *dictionaryResponse))success completionHandlerFailure:(void (^)(NSError *error))failure;

@end

APIManagerNew.m

@implementation APIManagerNew

#define USE_PRODUCTION_URL 0

#if USE_PRODUCTION_URL

static NSString *const BASE_URL = @”http://cherishgold.com/cherishws/&#8221;;

#else

static NSString *const BASE_URL = @”http://shagunn.info/cherishws/&#8221;;

#endif

NSString *const USERREGISTRATION = @”webservices/userRegistration”;

+ (APIManagerNew *)sharedAPIManager{

    static APIManagerNew *sharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[APIManagerNew alloc]init];

    });

    return sharedInstance;

    //    static NetworkManager *sharedNetworkManager = nil;

    //    static dispatch_once_t oncePredicate;

    //    dispatch_once(&oncePredicate, ^{

    //

    //        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

    //        [sharedNetworkManager setupServerConnection];

    //        [sharedNetworkManager.reachabilityManager startMonitoring];

    //

    //    });

    //

    //    return sharedNetworkManager;

}

– (void)hitAPIuserRegistrationParameters:(NSDictionary *)dictionaryParameters currentView:(UIView *)view completionHandlerSuccess:(void (^)(NSDictionary *dictionaryResponse))success completionHandlerFailure:(void (^)(NSError *error))failure{

    NSLog(@”%@”,dictionaryParameters);

    if ([Utility_ObjectiveC isInternetConnected_ShowPopupIfNotConnected:true]){

        [MBProgressHUD showHUDAddedTo:view animated:true];

        self.manager = [AFHTTPSessionManager manager];

        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];

        [self.manager.requestSerializer setValue:@”0a04775a6632aa79877659e5e6cd00dda67bf937_020254001488365421″ forHTTPHeaderField:@”Auth-Token”];

        [self.manager GET:[NSString stringWithFormat:@”%@%@”,BASE_URL,@”mobileapi/product_detail”] parameters:dictionaryParameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {

            [MBProgressHUD hideHUDForView:view animated:true];

            NSLog(@”JSON: %@”, responseObject);

//            BaseClass *baseClassObject = [[BaseClass alloc]initWithDictionary:responseObject];

//            NSLog(@”%@”,baseClassObject);

//

//            NSLog(@”%@”,baseClassObject.data);

//            NSLog(@”%@”,[[baseClassObject.data objectAtIndex:0] valueForKey:@”productId”]);

            ProductDetailDataModel *productDetailDataModelObject = [[ProductDetailDataModel alloc]initWithDictionary:[responseObject valueForKey:@”data”]];

            NSLog(@”%@”,productDetailDataModelObject);

            success(responseObject);

        } failure:^(NSURLSessionTask *operation, NSError *error) {

            [MBProgressHUD hideHUDForView:view animated:true];

            NSLog(@”Error: %@”, error);

            [Utility_ObjectiveC showAlertControllerwithTitle:nil Message:[error localizedDescription]];

            failure(error);

        }];

    }

}

@end

ViewController.m

#import “APIManagerNew.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    /*

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager GET:@”http://shagunn.info/cherishws/mobileapi/listMenus” parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {

        NSLog(@”JSON: %@”, responseObject);

    } failure:^(NSURLSessionTask *operation, NSError *error) {

        NSLog(@”Error: %@”, error);

    }];

     */

    NSDictionary *dictionaryParameter = @{@”product_id”:@”4147″,

                                          @”custom_id”:@”SI-IJ”,

                                          @”gcolor”:@”Yellow”,

                                          @”size”:@”7″,

                                          @”customer_id”:@”102″,

                                          @”metal_purity”:@”18″};

    NSLog(@”%@”,dictionaryParameter);

    [[APIManagerNew sharedAPIManager] hitAPIuserRegistrationParameters:dictionaryParameter currentView:self.view completionHandlerSuccess:^(NSDictionary *dictionaryResponse) {

        NSLog(@”%@”,dictionaryResponse);

        ProductDetailDataModel *productDetailDataModelObject = [[ProductDetailDataModel alloc]initWithDictionary:[dictionaryResponse valueForKey:@”data”]];

        NSLog(@”%@”,productDetailDataModelObject);

    } completionHandlerFailure:^(NSError *error) {

        NSLog(@”%@”,error);

    }];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

Download sample project

Hit api and get Responce and convert Response in DataModel

APIManagerNew.h

#import <Foundation/Foundation.h>

#import “MBProgressHUD.h”

#import “Utility_ObjectiveC.h”

#import “AFNetworking.h”

#import “ProductDetailAllDataModels.h”

@interface APIManagerNew : NSObject

@property AFHTTPSessionManager *manager;

+ (APIManagerNew *)sharedAPIManager;

– (void)hitAPIuserRegistrationParameters:(NSDictionary *)dictionaryParameters currentView:(UIView *)view completionHandlerSuccess:(void (^)(NSDictionary *dictionaryResponse))success completionHandlerFailure:(void (^)(NSError *error))failure;

@end

APIManagerNew.m

@implementation APIManagerNew

#define USE_PRODUCTION_URL 0

#if USE_PRODUCTION_URL

static NSString *const BASE_URL = @”http://cherishgold.com/cherishws/&#8221;;

#else

static NSString *const BASE_URL = @”http://shagunn.info/cherishws/&#8221;;

#endif

NSString *const USERREGISTRATION = @”webservices/userRegistration”;

+ (APIManagerNew *)sharedAPIManager{

    static APIManagerNew *sharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[APIManagerNew alloc]init];

    });

    return sharedInstance;

    //    static NetworkManager *sharedNetworkManager = nil;

    //    static dispatch_once_t oncePredicate;

    //    dispatch_once(&oncePredicate, ^{

    //

    //        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

    //        [sharedNetworkManager setupServerConnection];

    //        [sharedNetworkManager.reachabilityManager startMonitoring];

    //

    //    });

    //

    //    return sharedNetworkManager;

}

– (void)hitAPIuserRegistrationParameters:(NSDictionary *)dictionaryParameters currentView:(UIView *)view completionHandlerSuccess:(void (^)(NSDictionary *dictionaryResponse))success completionHandlerFailure:(void (^)(NSError *error))failure{

    NSLog(@”%@”,dictionaryParameters);

    if ([Utility_ObjectiveC isInternetConnected_ShowPopupIfNotConnected:true]){

        [MBProgressHUD showHUDAddedTo:view animated:true];

        self.manager = [AFHTTPSessionManager manager];

        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];

        [self.manager.requestSerializer setValue:@”0a04775a6632aa79877659e5e6cd00dda67bf937_020254001488365421″ forHTTPHeaderField:@”Auth-Token”];

        [self.manager GET:[NSString stringWithFormat:@”%@%@”,BASE_URL,@”mobileapi/product_detail”] parameters:dictionaryParameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {

            [MBProgressHUD hideHUDForView:view animated:true];

            NSLog(@”JSON: %@”, responseObject);

//            BaseClass *baseClassObject = [[BaseClass alloc]initWithDictionary:responseObject];

//            NSLog(@”%@”,baseClassObject);

//

//            NSLog(@”%@”,baseClassObject.data);

//            NSLog(@”%@”,[[baseClassObject.data objectAtIndex:0] valueForKey:@”productId”]);

            ProductDetailDataModel *productDetailDataModelObject = [[ProductDetailDataModel alloc]initWithDictionary:[responseObject valueForKey:@”data”]];

            NSLog(@”%@”,productDetailDataModelObject);

            success(responseObject);

        } failure:^(NSURLSessionTask *operation, NSError *error) {

            [MBProgressHUD hideHUDForView:view animated:true];

            NSLog(@”Error: %@”, error);

            [Utility_ObjectiveC showAlertControllerwithTitle:nil Message:[error localizedDescription]];

            failure(error);

        }];

    }

}

@end

ViewController.m

#import “APIManagerNew.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    /*

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager GET:@”http://shagunn.info/cherishws/mobileapi/listMenus” parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {

        NSLog(@”JSON: %@”, responseObject);

    } failure:^(NSURLSessionTask *operation, NSError *error) {

        NSLog(@”Error: %@”, error);

    }];

     */

    NSDictionary *dictionaryParameter = @{@”product_id”:@”4147″,

                                          @”custom_id”:@”SI-IJ”,

                                          @”gcolor”:@”Yellow”,

                                          @”size”:@”7″,

                                          @”customer_id”:@”102″,

                                          @”metal_purity”:@”18″};

    NSLog(@”%@”,dictionaryParameter);

    [[APIManagerNew sharedAPIManager] hitAPIuserRegistrationParameters:dictionaryParameter currentView:self.view completionHandlerSuccess:^(NSDictionary *dictionaryResponse) {

        NSLog(@”%@”,dictionaryResponse);

        ProductDetailDataModel *productDetailDataModelObject = [[ProductDetailDataModel alloc]initWithDictionary:[dictionaryResponse valueForKey:@”data”]];

        NSLog(@”%@”,productDetailDataModelObject);

    } completionHandlerFailure:^(NSError *error) {

        NSLog(@”%@”,error);

    }];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

Download sample project

 

How use Sourcetree

https://www.sourcetreeapp.com/

of to start now

creat account in https://bitbucket.org/

download source tree

Open Source tree

Click on setting icon

Go to Account – Accounts – Add

Click on connect account login with Bitbucket Account

In Protocol option select HTTP

OK

click on New Repository

Click on Clone from url

Source URL Paste URL from Bitbucket site – Repositories – Actions – Clone

Select destination path

Click on Clone

Error App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app’s Info.plist file.

Error

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app’s Info.plist file.

Solution

Go to info.plist

Go to abow

</dict>

</plist>

pase this code

<key>NSAppTransportSecurity</key>

<dict>

<key>NSAllowsArbitraryLoads</key>

<true/>

</dict>

add / Remove CocoaPods in Project

Steps to setup the CocoaPods

Open Terminal

CocoaPods runs on ruby so update your system.

sudo gem update –system

Install CocoaPods

Install CocoaPods by using following command :

sudo gem install cocoapods

If you are facing issue in EL Capitan or macOS Sierra then use following command :

sudo gem install -n /usr/local/bin cocoapods

Setup the Pod

pod setup

Note : This process will take some time.

Steps to add Alamofire and SwiftyJSON Pods to your project

Open Terminal

Navigate to the directory containing your AlamofireSwiftyJSONSample project by using the cd command:

cd ~/Path/To/Folder/Containing/AlamofireSwiftyJSONSample

Give the init command

pod init

It will create Podfile in your project’s directory.

Open the Podfile using command Or Open directly with double click on “Podfile” in project folder

open -a Xcode Podfile

Edit the pod file with your pods which you want to use and must remember the targets. Add pods to the particular target where you want to use that pod.

In Swift you have to add one more line use_frameworks!

So, Your Podfile will look like as :

Below code change “AlamofireSwiftyJSONSample”, “AlamofireSwiftyJSONSampleTests”, “AlamofireSwiftyJSONSampleUITests” To Project name

platform :ios, ‘9.0’

use_frameworks!

target ‘AlamofireSwiftyJSONSample’ do

    pod ‘Alamofire’

    pod ‘SwiftyJSON’

end

target ‘AlamofireSwiftyJSONSampleTests’ do

end

target ‘AlamofireSwiftyJSONSampleUITests’ do

end

Go to terminal and give following command

1

pod install

Note : From now you have to use the .xcworkspace of your project.

Let’s use it in our project

remove CocoaPods from a project?

open terminal

cd /Users/leooverseas/Desktop/CherishGold

sudo gem install cocoapods-deintegrate cocoapods-clean

pod deintegrate

pod clean

rm Podfile

dixnary //json file

{

“widget”:
{
“window”:
{

“title”: “Sample Konfabulator Widget”, “name”: “main_window”,
”width”: 500,

“height”: 500
},

“image”:
{
”src”: “Images/Sun.png”, “name”: “sun1”, “hOffset”: 250, “vOffset”: 250, “alignment”: “center”

}
}

}
dic=[NSJSONSerialization JSONObjectWithData:dta options:NSJSONReadingMutableContainers error:&error];

dic1=[dic valueForKeyPath:@”widget”];
arr1=(NSMutableArray *)[dic1 allKeys];
or
arr1=[dic1 allKeys];

arr2=[dic allValues];

dic3=[dic valueForKeyPath:@”widget.window”]; or
dic3=[dic valueForKeyPath:@”widget.image”];

in tableview cell print

cell.textLabel.text=(NSString *)[arr1 objectAtIndex:indexPath.row];

cell.detailTextLabel.text=[NSString stringWithFormat:@”%@”,[arr2 objectAtIndex:indexPath.row]];

UISearchBar

<UISearchBarDelegate> NSMutableArray *arr1,*arrreslt;

NSString *str1; BOOL issearching;

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

if (issearching)
{
return arrreslt.count;

}
else
{

return arr1.count;
}

// return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

if (issearching)
{

cell.textLabel.text = [arrreslt objectAtIndex:indexPath.row];
}

else{
cell.textLabel.text = [arr1 objectAtIndex:indexPath.row];

}

return cell;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

[arrreslt removeAllObjects]; issearching = TRUE;
for (NSString *str in arr1)
{

NSRange rang = [str rangeOfString:searchText]; if (rang.length > 0 && rang.location == 0)
{

[arrreslt addObject:str];
}

}

[tblview reloadData];
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar

{
[searchBar setShowsCancelButton:YES];
[searchBar setShowsBookmarkButton:YES];
return YES;

}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{

[searchBar resignFirstResponder]; }

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ [searchBar resignFirstResponder];
issearching = false;
[tblview reloadData];

}

Or

NSMutableArray *arr,*arrfiltr; NSString *strng1,*strng2;

BOOL isserarching;

arr=[[NSMutableArray alloc]initWithObjects:@”beach”,@”civic”,@”family”,@”happy”,@”icecream”, @”nature”,@”rose”,@”sport”,@”valentine”, nil];

arrfiltr=[[NSMutableArray alloc]init]; if (isserarching)

return [arrfiltr count];

return [arr count]; if (isserarching)
{

cell.textLabel.text=[arrfiltr objectAtIndex:indexPath.row];
}

else{
cell.textLabel.text=[arr objectAtIndex:indexPath.row];

}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

if (searchText.length>0) { isserarching = YES;
[arrfiltr removeAllObjects]; for (int i=0; i<arr.count; i++)
{

NSString *strng=[arr objectAtIndex:i];

NSRange rng=[strng rangeOfString:searchText options:NSCaseInsensitiveSearch];

if (rng.location != NSNotFound) { [arrfiltr addObject:strng];

}
}

}

Else
{

isserarching = NO;
}

[tblview reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];

}

Add maltiple button using for loop

UIButton *btn; int xi,yi,b; b=1;
xi=10; yi=10;

for (int a=1; a<=5; a++)
{
for (int i=1; i<=5; i++)
{

btn=[[UIButton alloc]init];

btn.backgroundColor=[UIColor blueColor];

btn.frame=CGRectMake(xi, yi, 50, 50);

[btn setTag:b];

[btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn]; xi+=60;
b++;

}
yi+=60; xi=10;

}

MVC – model view control

//apps will come from background to

//apps pause than come in active mode //apps terminate

Model = the class that hold your apolication data

View = made with windows, controls and elements that user can see and interept with

Controller = the code that bind togather model and view, it contains the application logic that decide how to handel user input

View Up Down for keyboard show Hide

<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *textFieldActive;

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self.view addGestureRecognizer:tapGesture];

#pragma mark – TextField Delegate

– (BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

    // return NO to disallow editing.

    return YES;

    

}

– (void)textFieldDidBeginEditing:(UITextField *)textField

{

    // became first responder

    _textFieldActive = textField;

    if (_textFieldActive != _textFieldReferalID && _textFieldActive != _textFieldMailingAddress) {

        //    iPhone = -210

        //    iPad = -230

        [self viewUpDownWithAnimationYCoordinate:-230];

    }

    

}

– (BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

    // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end

    return YES;

}

– (void)textFieldDidEndEditing:(UITextField *)textField

{

    // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    [_textFieldActive resignFirstResponder];

    [self viewUpDownWithAnimationYCoordinate:0];

}

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

{

    // return NO to not change text

    return YES;

    

}

– (BOOL)textFieldShouldClear:(UITextField *)textField

{

    // called when clear button pressed. return NO to ignore (no notifications)

    return NO;

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // called when ‘return’ key pressed. return NO to ignore.

    [_textFieldActive resignFirstResponder];

    return YES;

}

– (void)viewUpDownWithAnimationYCoordinate:(float)yCoordinare

{

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:0.35f];

    CGRect frame = self.view.frame;

    frame.origin.y = yCoordinare;

    [self.view setFrame:frame];

    [UIView commitAnimations];

    

}

#pragma mark –

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [_textFieldActive resignFirstResponder];

    [self.view endEditing:YES];// this will do the trick

    

}

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    [_textFieldActive resignFirstResponder];

    

}

View Constraint set Programetically

UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];

    redView.backgroundColor = [UIColor redColor];

    redView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:redView];

    // Width

    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:200]];

    // Height

    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:100]];

    // X

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];

    // Y

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];

    [self.view addSubview:redView];

UITapGestureRecognizer Example

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapGestureRecognizerEvent:)];

    [self.view addGestureRecognizer:tapGestureRecognizer];

#pragma mark –

– (void)handleTapGestureRecognizerEvent:(UITapGestureRecognizer *)tapGestureRecognizer

{

    [_textFieldActive resignFirstResponder];

    

}

UITapGestureRecognizer breaks UITableView didSelectRowAtIndexPath

<UIGestureRecognizerDelegate>

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapGestureRecognizer:)];

    tapGesture.delegate = self;

    [self.view addGestureRecognizer:tapGesture];

#pragma mark UIGestureRecognizerDelegate methods

– (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

{

    if ([touch.view isDescendantOfView:_tableView]) {

        

        // Don’t let selections of auto-complete entries fire the

        // gesture recognizer

        return NO;

    }

    

    return YES;

}

In two Button (Male / Female) Find out if first button selected second button should be unselected if second button selected first button should be unselected

two buttons Male and Female

Male button in Storyboard

Inspector area – State Config – Default

Male Button BackGround – Round_UnSelected // Set image

Inspector area – State Config – Selected

Male Button BackGround – Round_Selected // Set image

Female button in Storyboard

Inspector area – State Config – Default

Female Button BackGround – Round_UnSelected // Set image

Inspector area – State Config – Selected

Female Button BackGround – Round_Selected // Set image

– (IBAction)buttonActionMale:(id)sender {

    if (!_buttonMale.selected)

    {

        _buttonMale.selected = !_buttonMale.selected;

    }

    _buttonFemale.selected = NO;

}

– (IBAction)buttonActionFemale:(id)sender {

    if (!_buttonFemale.selected)

    {

        _buttonFemale.selected = !_buttonFemale.selected;

    }

    _buttonMale.selected = NO;

}

– (void)getMaleFemaleSelectedDetail

{

    

    if (self.buttonMale.selected)

    {

        NSLog(@”Male”);

        

    }

    

    else if(self.buttonFemale.selected)

    {

        NSLog(@”Female”);

        

    }

    

}

Create Vcard File / Create .vcf File

Contacts, NSDocumentDirectory

#import <Contacts/Contacts.h>

– (IBAction)btnCreatevcfFileClicked:(id)sender

{

    NSString *vcard = @”BEGIN:VCARDnVERSION:3.0n”;

    

    // Name

    vcard = [vcard stringByAppendingFormat:@”N:%@;%@;%@;%@;%@n”,

             @”lastname”, //lastname

             @”firstname”, //firstname

             @”middlename”, //middlename

             @”prefix”, //prefix

             @”suffix” //suffix

             ];

    

    vcard = [vcardstringByAppendingFormat:@”FN:%@n”,@”compositeName”];//compositeName

    vcard = [vcardstringByAppendingFormat:@”NICKNAME:%@n”,@”nickname”]; //nickname

    vcard = [vcard stringByAppendingFormat:@”X-PHONETIC-FIRST-NAME:%@n”,@”firstnamephonetic”]; //firstnamephonetic

    vcard = [vcard stringByAppendingFormat:@”X-PHONETIC-LAST-NAME:%@n”,@”lastnamephonetic”]; //lastnamephonetic

    

    

    // Work

    vcard = [vcardstringByAppendingFormat:@”ORG:%@;%@n”,@”organization”,@”department”];//organization, department

    vcard = [vcard stringByAppendingFormat:@”TITLE:%@n”,@”jobtitle”];//jobtitle

    

    // Mail

    vcard = [self emailToVcardFieldEmail:@”email1@gmail.com”label:@”HOME” emailCounter:1 vCard:vcard]; //email, emailLabel

    vcard = [self emailToVcardFieldEmail:@”email2@gmail.com”label:@”WORK” emailCounter:2 vCard:vcard]; //email, emailLabel

    

    // Tel

    vcard = [self phoneToVcardFieldPhoneNo:@”1111111111″ label:@”MOBILE”phoneCounter:1 vCard:vcard]; //phone no, phoneLabel

    vcard = [self phoneToVcardFieldPhoneNo:@”2222222222″ label:@”MAIL”phoneCounter:2 vCard:vcard]; //phone no, phoneLabel

    vcard = [self phoneToVcardFieldPhoneNo:@”3333333333″label:@”IPHONE” phoneCounter:3 vCard:vcard]; //phone no, phoneLabel

    vcard = [self phoneToVcardFieldPhoneNo:@”4444444444″label:@”WORKFAX” phoneCounter:4 vCard:vcard]; //phone no, phoneLabel

    

    

   //  Adress

    NSDictionary *address1 = [[NSDictionary alloc]initWithObjectsAndKeys:

                             @”St Jhons”, @”Street”,

                             @”San Fransisco”, @”City”,

                             @”California”, @”State”,

                             @”27105″, @”ZIP”,

                             @”USA”, @”Country”,

                             @”1″, @”CountryCode”, nil];

    

    vcard = [self addressToVcardFieldAddress:address1 label:@”HOME”AddressCounter:1 vCard:vcard];

    

    NSDictionary *address2 = [[NSDictionary alloc]initWithObjectsAndKeys:

                             @”St Jhons”, @”Street”,

                             @”San Fransisco”, @”City”,

                             @”California”, @”State”,

                             @”27105″, @”ZIP”,

                             @”USA”, @”Country”,

                             @”1″, @”CountryCode”, nil];

     vcard = [self addressToVcardFieldAddress:address2 label:@”WORK”AddressCounter:2 vCard:vcard];

    

    // url

    vcard = [self urlToVcardFieldURL:@”www.apple.com” label:@”HOME”URLCounter:1 vCard:vcard]; //url, urlLabel

    vcard = [self urlToVcardFieldURL:@”www.google.com” label:@”WORK”URLCounter:2 vCard:vcard]; //url, urlLabel

    

    

    

    // IM SMS

    NSDictionary *im = [[NSDictionary alloc]initWithObjectsAndKeys:

                        @”Apple Service”, @”service”,

                        @”Apple User Name”, @”username”, nil];

    

    vcard = [self imToVcardFieldIm:im label:@”HOME” IMCounter:1vCard:vcard]; //sms, smsLabel

    

    

    

    // birthday

    NSDate *birthday = @”1/1/2011″; //birthday

    if (birthday)

    {

        NSString *bday = [NSString stringWithFormat:@”%@”,birthday];

        NSArray *bdayArr = [bday componentsSeparatedByString:@” “];

        bday = [bdayArr objectAtIndex:0];

        

        vcard = [vcardstringByAppendingFormat:@”BDAY;value=date:%@n”,bday];

    }

    // Photo

    NSData *imageData = UIImageJPEGRepresentation([UIImageimageNamed:@”Own_Selected”], 0.0);//imageData;

    if (imageData)

    {

        vcard = [vcard stringByAppendingFormat:@”PHOTO;BASE64:%@n”,[imageData base64Encoding]];

    }

    

    

    

    

    // end

    vcard = [vcard stringByAppendingString:@”END:VCARD”];

    

        NSLog(@”%@”,vcard);

    

        NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

        NSLog(@”%@”,documentsDirectory);

        NSError *error;

        BOOL succeed = [vcard writeToFile:[documentsDirectorystringByAppendingPathComponent:@”contact.vcf”]

                                      atomically:YES encoding:NSUTF8StringEncodingerror:&error];

        if (!succeed){

            // Handle error here

            NSLog(@”Error”);

        }

    

    

    

    

    

}

– (NSString *)emailToVcardFieldEmail:(NSString *)email label:(NSString*)label emailCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    // label = Home

    // label = WORK

    

    NSString *labelLower = [label lowercaseString];

    

    

    if ([labelLower isEqualToString:@”_$!<home>!$_”]) vcard = [NSStringstringWithFormat:@”EMAIL;type=INTERNET;type=HOME:%@n”,email];

    else if ([labelLower isEqualToString:@”_$!<work>!$_”]) vcard = [NSStringstringWithFormat:@”EMAIL;type=INTERNET;type=WORK:%@n”,email];

    else

    {

        vcard = [vcardstringByAppendingFormat:@”item%d.EMAIL;type=INTERNET:%@nitem%d.X-ABLabel:%@n”,counter,email,counter,label];

    }

    return vcard;

}

– (NSString *)phoneToVcardFieldPhoneNo:(NSString *)phone label:(NSString*)label phoneCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    //MOBILE

    //IPHONE

    //HOME

    //WORK

    //MAIN

    //HOMEFAX

    //WORKFAX

    //PAGER

    

    

    

    NSString *labelLower = [label lowercaseString];

   

    

    if ([labelLower isEqualToString:@”_$!<mobile>!$_”]) vcard = [NSStringstringWithFormat:@”TEL;type=CELL:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<iphone!$_”]) vcard = [NSStringstringWithFormat:@”TEL;type=IPHONE:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<home>!$_”]) vcard = [NSStringstringWithFormat:@”TEL;type=HOME:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<work>!$_”]) vcard = [NSStringstringWithFormat:@”TEL;type=WORK:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<main>!$_”]) vcard = [NSStringstringWithFormat:@”TEL;type=MAIN:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<homefax>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=HOME;type=FAX:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<workfax>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=WORK;type=FAX:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<pager>!$_”]) vcard = [NSStringstringWithFormat:@”TEL;type=PAGER:%@n”,phone];

    else

    {

       //        if not showing phone number in outlook express in window use below code

//        vcard = [vcard stringByAppendingFormat:@”TEL;TYPE=%@,VOICE:%@n”,label,phone];

        vcard = [vcard stringByAppendingFormat:@”item%d.TEL:%@nitem%d.X-ABLabel:%@n”,counter,phone,counter,label];

        

    }

    

    return vcard;

}

– (NSString *)addressToVcardFieldAddress:(NSDictionary *)address label:(NSString *)label AddressCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    //WORK

    //HOME

    

    NSString *labelField = @””;

    NSString *labelLower = [label lowercaseString];

    NSString *type = @”HOME”;

    

    //

    if([labelLower isEqualToString:@”_$!<work>!$_”]) type = @”WORK”;

    else if([labelLower isEqualToString:@”_$!<home>!$_”]) {}

    else if( label && [label length] > 0 )

    {

        labelField = [NSString stringWithFormat:@”item%d.X-ABLabel:%@n”,counter,label];

    }

    

    //

    NSString *street = [address objectForKey:@”Street”] ? [addressobjectForKey:@”Street”] : @””;

    if ([street rangeOfString:@”n”].location != NSNotFound)

    {

        NSArray *arr = [street componentsSeparatedByString:@”n”];

        street = [arr componentsJoinedByString:@”\n”];

    }

    

    NSString *City = [address objectForKey:@”City”] ? [addressobjectForKey:@”City”] : @””;

    NSString *State = [address objectForKey:@”State”] ? [addressobjectForKey:@”State”] : @””;

    NSString *ZIP = [address objectForKey:@”ZIP”] ? [addressobjectForKey:@”ZIP”] : @””;

    NSString *Country = [address objectForKey:@”Country”] ? [addressobjectForKey:@”Country”] : @””;

    NSString *CountryCode = [address objectForKey:@”CountryCode”] ? [address objectForKey:@”CountryCode”] : @””;

    

    

    //

    vcard = [vcardstringByAppendingFormat:@”item%d.ADR;type=%@:;;%@;%@;%@;%@;%@n%@item%d.X-ABADR:%@n”,

             counter,

             type,

             street,

             City,

             State,

             ZIP,

             Country,

             labelField,

             counter,

             CountryCode

             ];

    

    //

   

    return vcard;

}

– (NSString *)urlToVcardFieldURL:(NSString *)url label:(NSString *)label URLCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    //HOME

    //WORK

    

    NSString *labelLower = [label lowercaseString];

    

    if ([labelLower isEqualToString:@”_$!<home>!$_”]) vcard = [NSStringstringWithFormat:@”URL;type=HOME:%@n”,url];

    else if ([labelLower isEqualToString:@”_$!<work>!$_”]) vcard = [NSStringstringWithFormat:@”URL;type=WORK:%@n”,url];

    else

    {

        

        vcard = [vcard stringByAppendingFormat:@”item%d.URL:%@nitem%d.X-ABLabel:%@n”,counter,url,counter,label];

    }

    

    return vcard;

}

– (NSString *)imToVcardFieldIm:(NSDictionary *)im label:(NSString *)label IMCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    

    //HOME

    //WORK

    

    

    NSString *labelLower = [label lowercaseString];

    

    NSString *service = [im objectForKey:@”service”] ? [imobjectForKey:@”service”] : @””;

    service = [service uppercaseString];

    

    NSString *username = [im objectForKey:@”username”] ? [imobjectForKey:@”username”] : @””;

    

    //

    if ([labelLower isEqualToString:@”_$!<home>!$_”] || [labelLowerisEqualToString:@”_$!<work>!$_”])

    {

        NSString *type = [labelLower isEqualToString:@”_$!<home>!$_”] ?@”HOME” : @”WORK”;

        vcard = [NSString stringWithFormat:@”X-%@;type=%@:%@n”,service,type,username];

    }

    

    else

    {

        vcard = [vcard stringByAppendingFormat:@”item%d.X-%@:%@nitem%d.X-ABLabel:%@n”,counter,service,username,counter,label];

    }

    

    return vcard;

}

Before Hit API set Secure connection

open Info.plist

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”&gt;

<plist version=”1.0″>

<dict>

<key>NSAllowsArbitraryLoads</key>

<true/>

<key>NSExceptionDomains</key>

<dict>

<key>akamaihd.net</key>

<dict>

<key>NSIncludesSubdomains</key>

<true/>

<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>

<false/>

</dict>

<key>facebook.com</key>

<dict>

<key>NSIncludesSubdomains</key>

<true/>

<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>

<false/>

</dict>

<key>fbcdn.net</key>

<dict>

<key>NSIncludesSubdomains</key>

<true/>

<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>

<false/>

</dict>

</dict>

</dict>

</plist>

Hit API with NSURLSession get response

<NSURLSessionDelegate>

-(void)getJsonResponse : (NSString *)urlStr success : (void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure

{

    

    

    NSURLSession * session = [NSURLSession sharedSession];

    NSURL * url = [NSURL URLWithString: urlStr];

    

    

    // Asynchronously Api is hit here

    NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)

                                       {

                                           

                                           NSLog(@”%@”,data);

                                           

                                           NSDictionary * json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

                                           NSLog(@”%@”,json);

                                           success(json);

                                           

                                           

                                           

                                       }];

    

    [dataTask resume] ; // Executed First

    

    

}

Attributed Label, Set html text on label

NSString * htmlString = @”<html><body>Apple is <b>great</b> <u>company</u> in USA</body></html>”;

    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc]initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding]options:@{ NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType } documentAttributes:nil error:nil];

       [attrStr addAttribute:NSForegroundColorAttributeName

                 value:[UIColor redColor]

                 range:NSMakeRange([attrStr length]-3, 3)];

        self.labelFirst.attributedText = attrStr;

UIAlertController with UITextField

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@”Enter Referance”

                                                                       message:nil

                                                                preferredStyle:UIAlertControllerStyleAlert];

        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            // optionally configure the text field

            textField.keyboardType = UIKeyboardTypeDefault;

        }];

        

        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@”OK”

                                                           style:UIAlertActionStyleDefault

                                                         handler:^(UIAlertAction *action) {

                                                             UITextField *textFieldEnterOtherReferance = [alertController.textFields firstObject];

                                                             NSLog(@”%@”,textFieldEnterOtherReferance.text);

                                                             if ([Utility trimString_RemoveWhiteSpaceFromString:textFieldEnterOtherReferance.text].length != 0)

                                                             {

                                                                 _labelReferance.text = textFieldEnterOtherReferance.text;

                                                             }

                                                             _viewPopUpBelowTable.hidden = YES;

                                                             _tableViewPopUp.hidden = YES;

                                                         }];

        [alertController addAction:okAction];

        [self presentViewController:alertController animated:YES completion:nil];

sqlite

//value change

//

select *from table_name
insert into table_name values (‘Mark’,’Za’,”,’ld’,’9111111111′) DELETE FROM table_name WHERE fname=’kaushik’

page88image11872.png ¬ page88image12480.png ¬ page88image13088.png ¬page88image13696.png ¬

//
WHERE fname=’kaushik’

UPDATE table_name set fname=’info’, lname=’soft’ ,standard=’pvt.ltd.’

// select *from table_name where fname=’kaushik’

 

 

-(void)checkdatafilepathandcopyfilepath:(NSString *)strfilepath filename:(NSString *)strfilename fileextentn:(NSString *)strfileextentn;

{

NSString *strdatapath=[NSHomeDirectory() stringByAppendingPathComponent:strfilepath];

NSLog(@”%@”,strdatapath); /*

if ([[NSFileManager defaultManager]fileExistsAtPath:strdatapath]) {

NSError *error;

[[NSFileManager defaultManager]removeItemAtPath:strdatapath error:&error];

}

*/
if (![[NSFileManager defaultManager]fileExistsAtPath:strdatapath]) {

NSString *strbndlpath=[[NSBundle mainBundle]pathForResource:strfilename ofType:strfileextentn];

NSError *error;

[[NSFileManager defaultManager]copyItemAtPath:strbndlpath toPath:strdatapath error:&error];

NSLog(@”sucessful copy %@”,error); }

}

-(NSMutableArray *)readsqlfiledatafilepath:(NSString *)strfilepath query:(NSString *)strquery;

{

NSString *strdatapath=[NSHomeDirectory() stringByAppendingPathComponent:strfilepath];

if (sqlite3_open([strdatapath UTF8String], &database)==SQLITE_OK) {

NSLog(@”database open”); // select *from table_name

NSString *strqry=strquery;

NSMutableArray *arr=[[NSMutableArray alloc]init];

sqlite3 *database;

sqlite3_stmt *complitestament;

if (sqlite3_prepare_v2(database, [strqry UTF8String], -1, &complitestament, NULL)==SQLITE_OK)

{
NSLog(@”table open”);
while (sqlite3_step(complitestament)==SQLITE_ROW) {

NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];

for (int i=0; i<sqlite3_column_count(complitestament); i++) {

NSString *strcolnam=[NSString stringWithUTF8String:(char*)sqlite3_column_name(complitestament, i)];

// NSLog(@”%@”,strcolnam);

NSString *strcoltxt=[NSString stringWithUTF8String:(char*)sqlite3_column_text(complitestament, i)];

// NSLog(@”%@”,strcoltxt);

[dic setObject:strcoltxt forKey:strcolnam]; }

// NSLog(@”dic :: %@”,dic);

[arr addObject:dic]; }

} }

// NSLog(@”arr :: %@”,arr); sqlite3_close(database);

return arr; }

-(void)addsqlfiledatafilepath:(NSString *)strfilepath query:(NSString *)strquery;

{

NSString *strdatapath=[NSHomeDirectory() stringByAppendingPathComponent:strfilepath];

if (sqlite3_open([strdatapath UTF8String], &database)==SQLITE_OK) {

sqlite3 *database;

//

NSLog(@”database open”);
insert into table_name values (‘Mark’,’Za’,’MBA’,’ld’,’9676283432′)

NSString *strqry=strquery;

sqlite3_stmt *complitestament;

if (sqlite3_prepare_v2(database, [strqry UTF8String], -1, &complitestament, NULL)==SQLITE_OK)

{
NSLog(@”table open”);
if (sqlite3_step(complitestament)==SQLITE_DONE) {

NSLog(@”added”); }

else

{
NSLog(@”error”);

} }

}

sqlite3_close(database); }

-(void)deletesqlfiledatafilepath:(NSString *)strfilepath query:(NSString *)strquery

{

NSString *strdatapath=[NSHomeDirectory() stringByAppendingPathComponent:strfilepath];

if (sqlite3_open([strdatapath UTF8String], &database)==SQLITE_OK) {

sqlite3 *database;

//

NSLog(@”database open”);
DELETE FROM table_name WHERE fname=’kaushik’

NSString *strqry=strquery;

sqlite3_stmt *complitestament;

if (sqlite3_prepare_v2(database, [strqry UTF8String], -1, &complitestament, NULL)==SQLITE_OK)

{
NSLog(@”table open”);

if (sqlite3_step(complitestament)==SQLITE_DONE) { NSLog(@”deleted”);

} else{

NSLog(@”error”); }

} }

sqlite3_close(database); }

-(void)updatesavesqlfiledatafilepath:(NSString *)strfilepath query:(NSString *)strquery

{

NSString *strdatapath=[NSHomeDirectory() stringByAppendingPathComponent:strfilepath];

if (sqlite3_open([strdatapath UTF8String], &database)==SQLITE_OK) {

NSLog(@”database open”);

// UPDATE form_table set fname=’info’, lname=’soft’ ,standard=’pvt.ltd.’ WHERE fname=’kaushik’

NSString *strqry=strquery; sqlite3_stmt *complitestament;

sqlite3 *database;

if (sqlite3_prepare_v2(database, [strqry UTF8String], -1, &complitestament, NULL)==SQLITE_OK)

{
NSLog(@”table open”);

if (sqlite3_step(complitestament)==SQLITE_DONE) { NSLog(@”updated”);

} else {

NSLog(@”error”); }

} }

sqlite3_close(database); }

-(NSMutableArray *)updateshowsqlfiledatafilepath:(NSString *)strfilepath query:(NSString *)strquery

{
NSMutableArray *arr=[[NSMutableArray alloc]init]; sqlite3 *database;

NSString *strdatapath=[NSHomeDirectory() stringByAppendingPathComponent:strfilepath];

if (sqlite3_open([strdatapath UTF8String], &database)==SQLITE_OK) {

NSLog(@”database open”);
// select *from table_name where fname=’kaushik’

NSString *strqry=strquery;

sqlite3_stmt *complitestament;

if (sqlite3_prepare_v2(database, [strqry UTF8String], -1, &complitestament, NULL)==SQLITE_OK)

{
NSLog(@”table open”);
while (sqlite3_step(complitestament)==SQLITE_ROW) {

NSMutableDictionary *dic=[[NSMutableDictionary alloc]init]; for (int i=0; i<sqlite3_column_count(complitestament); i++)
{

NSString *strcolnam=[NSString stringWithUTF8String:(char*)sqlite3_column_name(complitestament, i)];

// NSLog(@”%@”,strcolnam);

NSString *strcoltxt=[NSString stringWithUTF8String:(char*)sqlite3_column_text(complitestament, i)];

// NSLog(@”%@”,strcoltxt);

[dic setObject:strcoltxt forKey:strcolnam]; }

// NSLog(@”dic :: %@”,dic); [arr addObject:dic];

} }

}
// NSLog(@”arr :: %@”,arr); sqlite3_close(database);

return arr; }

Sqlite connection file .h

#import <Foundation/Foundation.h>

#import <sqlite3.h>

@interface sqliteconnecton : NSObject

{

NSMutableArray *data;

}

-(NSMutableArray *)selectrecord:(NSString *)dbpath SelectQuery:(NSString *)query ;

-(NSString *)IUDrecord:(NSString *)dbpath SelectQuery:(NSString *)query ;

@end

.m file

#import “sqliteconnecton.h”

#import <sqlite3.h>

@implementation sqliteconnecton

-(NSMutableArray *)selectrecord:(NSString *)dbpath SelectQuery:(NSString *)query{

 

data = [[NSMutableArray alloc]init];

sqlite3 *db;

 

 

int i;

if (sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK)

{

NSString *strqury = query;

NSMutableDictionary *dict1;

sqlite3_stmt *statementss;

if (sqlite3_prepare_v2(db, [strqury UTF8String], -1, &statementss, nil)==SQLITE_OK)

{

while (sqlite3_step(statementss)==SQLITE_ROW)

{

dict1 =[[NSMutableDictionary alloc]init];

for (i=0; i<sqlite3_column_count(statementss); i++)

{

 

NSString *strcolumnname = [NSStringstringWithUTF8String:sqlite3_column_name(statementss, i)];

NSString *strcolumndata = [NSStringstringWithUTF8String:(char*)sqlite3_column_text(statementss, i)];

[dict1 setObject:strcolumndataforKey:strcolumnname];

}

[data addObject:dict1];

}

}

sqlite3_close(db);

}

return data;

}

-(NSString *)IUDrecord:(NSString *)dbpath SelectQuery:(NSString *)query{

sqlite3 *d1;

NSString *message;

if (sqlite3_open([dbpath UTF8String], &d1) ==SQLITE_OK)

{

NSLog(@”Database Open”);

sqlite3_stmt *completedStatement;

 

if (sqlite3_prepare_v2(d1, [query UTF8String], -1, &completedStatement, NULL) == SQLITE_OK)

{

if (sqlite3_step(completedStatement) ==SQLITE_DONE)

{

message = @”Success”;

sqlite3_close(d1);

}

else

{

message = @”error”;

}

}

else {

message =@”error”;

}

 

}

return message;

}

@end

appdelegate:

-(void) addFile

{

NSString *strpath = [@”~/Documents/Databese.sqlite”stringByExpandingTildeInPath];

NSLog(@”%@”,strpath);

NSError *err;

if (![[NSFileManager defaultManager]fileExistsAtPath:strpath])

{

NSString *str = [[NSBundlemainBundle]pathForResource:@”Databese”ofType:@”sqlite”];

[[NSFileManagerdefaultManager]copyItemAtPath:str toPath:strpatherror:&err];

}

else

{

NSLog(@”Already Exist…….”);

}

}

in h and m file

first create sqlite object and init then

NSString * dbpath = [NSHomeDirectory()stringByAppendingPathComponent:@”Documents/Databese.sqlite”];

NSString *strQuery=[NSStringstringWithFormat:@”insert into USER_REGISTRATION (FirstName,LastName, EmailId, Password,ConformPassword,Gender,DateOfBirth) values(‘%@’,’%@’, ‘%@’,’%@’,’%@’,’%@’,’%@’)”,txtfname.text,txtlname.text,txtemailid.text,txtpassword.text,txtconforpassword.text,txtgender.text,txtdate.text];

NSString * insert =[con IUDrecord:dbpathSelectQuery:strQuery];

NSLog(@”%@”,insert);

 

if ([txtpassword.text isEqual:txtconforpassword.text]) {

loginpage * login =[self.storyboardinstantiateViewControllerWithIdentifier:@”loginpage”];

[self.navigationControllerpushViewController:login animated:YES];

custom delegate

data send from third viewcontroller to second viwecontroller thirdviewcontroller.h file
@protocol threetotwo <NSObject> -(void)senddtthretotwo:(NSString *)string1;

@end
@property (nonatomic,strong) id<threetotwo>str1;thirdviewcontroller.m file
[str1 senddtthretotwo:txt3.text];

secindviewcontroller.h file

<threetotwo>

secindviewcontroller.m file

-(void)senddtthretotwo:(NSString *)string1 {

lbl2.text=string1;

=}

ViewController method use in newViewController newViewController.h
-(void)print;

ViewController.m -(void)print;
{

NSLog(@”kaushik info soft”); }

newViewController.m
ViewController *vwct=[[ViewController alloc]init]; [vwct print];

UILocalNotification
IBOutlet UIDatePicker *datpkr;
- (IBAction)btnadnotific:(id)sender {

NSDate *dtobj=[datpkr date]; NSLog(@”%@”,dtobj);

UILocalNotification *local=[[UILocalNotification alloc]init];

// local.fireDate=[NSDate dateWithTimeIntervalSinceNow:30];

local.fireDate=dtobj; //currant system date and set notification local.alertBody=@”kaushik info soft pvt ltd creat”;
[[UIApplication sharedApplication]scheduleLocalNotification:local];

}

A V AudioPlayer
#import <AVFoundation/AVFoundation.h>

AVAudioPlayer *audopl; IBOutlet UISlider *sldref;

NSString *strflpath=[[NSBundle mainBundle]pathForResource:@”Mausam_Flute” ofType:@”mp3″];

NSURL *url=[NSURL fileURLWithPath:strflpath];
NSError *error;
audopl=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error]; audopl.delegate=self;

audopl.volume=0.5;

[audopl play]; [audopl pause]; [audopl stop];

audopl.numberOfLoops=4;

– (IBAction)sldrval:(id)sender {

audopl.volume=sldref.value; }

UIActivityViewController

send all -facebook, twitter, mail -message with image

UIImage *img=[UIImage imageNamed:@”celebrate-success.png”];

NSArray *arr1=[[NSArray alloc]initWithObjects:@”kaushik”,@”info”,@”soft”,img, nil];

UIActivityViewController *actvwct=[[UIActivityViewController alloc]initWithActivityItems:arr1 applicationActivities:nil];

[self presentViewController:actvwct animated:YES completion:nil];

splash screen

splash_screen-Info.plist file end + button
Launch image positive-quotes.jpg

appdelegate.h

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

sleep(3);
// Override point for customization after application launch. return YES;

}

MailCompose

<MFMailComposeViewControllerDelegate>
// if ([MFMailComposeViewController canSendMail]) {

MFMailComposeViewController *mailvc=[[MFMailComposeViewController alloc]init];

mailvc.mailComposeDelegate=self;

[mailvc setSubject:@”kaushik”];

[mailvc setToRecipients:[[NSArray alloc]initWithObjects:@”kaushik@gmail.com”,@”rajdip@gmail.com”, nil]];

[mailvc setBccRecipients:[[NSArray alloc]initWithObjects:@”info@gmail.com”,@”soft@gmail.com”, nil]];

[mailvc setMessageBody:@”<u><b>pvt ltd company<b><u>” isHTML:YES];

UIImage *img=[UIImage imageNamed:@”airindiaexpress.jpg”]; NSData *data=UIImageJPEGRepresentation(img, CGFLOAT_MIN);

[mailvc addAttachmentData:data mimeType:@”image/jpg” fileName:@”plane”];

[self presentViewController:mailvc animated:YES completion:nil];

//  }

//  else

//  {

//  NSLog(@”connect internet”);

//  } 
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error 
{
if (result == MFMailComposeResultCancelled) {
NSLog(@”MFMailComposeResultCancelled”); }
else if (result == MFMailComposeResultSaved) {
NSLog(@”MFMailComposeResultSaved”); } 
else if (result == MFMailComposeResultSent) {
NSLog(@”MFMailComposeResultSent”);

}
else if (result == MFMailComposeResultFailed) {

NSLog(@”MFMailComposeResultFailed”); }

[self dismissViewControllerAnimated:YES completion:nil]; }

MKMapView delegate

<MKMapViewDelegate,CLLocationManagerDelegate> CLLocationManager *locmngr;

– (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation

{

MKAnnotationView *mkvw=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@”k”];

mkvw.image=[UIImage imageNamed:@”feel_freedom.jpg”];

MKPinAnnotationView *pinano=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@”k”];

pinano.pinColor=MKPinAnnotationColorPurple;

return mkvw; // return pinano;

}

–  (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(@”%@”,locations); 
}

–  (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error; {
NSLog(@”%@”,error); }

xml parser

<NSXMLParserDelegate> NSXMLParser *xmprsr;

NSMutableArray *arrttl,*arrlnk,*arrdescr; NSString *str1,*strtmp; arrttl=[[NSMutableArray alloc]init];

imgselect=[info objectForKey:UIImagePickerControllerOriginalImage]; imgselect=[info objectForKey:UIImagePickerControllerEditedImage]; imgvw.image=imgselect;

arrlnk=[[NSMutableArray alloc]init]; arrdescr=[[NSMutableArray alloc]init];

// NSString *strpath=[[NSBundle mainBundle]pathForResource:@”resume_w_xsl” ofType:@”xml”];

// NSURL *url=[NSURL fileURLWithPath:strpath];

NSURL *url=[NSURL URLWithString:@”http://www.rediff.com/rss/inrss.xml”%5D;

xmprsr =[[NSXMLParser alloc]initWithContentsOfURL:url]; xmprsr.delegate=self;
[xmprsr parse];

-(void)parserDidStartDocument:(NSXMLParser *)parser {

// NSLog(@”start”); }

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

{
// NSLog(@”%@”,elementName);

strtmp=elementName; }

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

{

// NSLog(@”%@”,elementName);
if ([strtmp isEqualToString:@”title”]) {

[arrttl addObject:str1]; }

else if ([strtmp isEqualToString:@”link”]) { [arrlnk addObject:str1];

}
else if ([strtmp isEqualToString:@”description”]) {

if (![str1 isEqual: @”\n”]) { [arrdescr addObject:str1];

} }

}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

// NSLog(@”%@”,string); str1=string;

}
-(void)parserDidEndDocument:(NSXMLParser *)parser {

// NSLog(@”end”); }

Image pick from gallery

<UIActionSheetDelegate,UIImagePickerControllerDelegate> IBOutlet UIImageView *imgvw;

UIImage *imgselect;
- (IBAction)btnsavimg:(id)sender {

UIImageWriteToSavedPhotosAlbum(imgvw.image, self, nil, nil);

}
// NSLog(@”photo gallery”);

UIImagePickerController *pckr=[[UIImagePickerController alloc]init];

pckr.delegate=self; pckr.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;

pckr.allowsEditing=TRUE;
[self presentViewController:pckr animated:TRUE completion:nil];

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
[self dismissViewControllerAnimated:YES completion:nil];

//

}

MPMoviePlayerController custom

#import <MediaPlayer/MediaPlayer.h> IBOutlet UIView *viw1;

MPMoviePlayerController *mpmvplr;

NSString *strflpath=[[NSBundle mainBundle]pathForResource:@”Test Your Brain” ofType:@”mp4″];

NSURL *url=[NSURL fileURLWithPath:strflpath]; mpmvplr=[[MPMoviePlayerController alloc]init]; [mpmvplr setContentURL:url];
[mpmvplr.view setFrame:viw1.bounds];

[viw1 addSubview:mpmvplr.view];

/*
[mpmvplr setMovieSourceType:MPMovieSourceTypeFile];

mpmvplr.view.backgroundColor=[UIColor greenColor];

// mpmvplr.scalingMode=MPMovieScalingModeNone;

mpmvplr.scalingMode=MPMovieScalingModeFill;

// mpmvplr.controlStyle=MPMovieControlStyleNone;
// mpmvplr.controlStyle=MPMovieControlModeDefault; mpmvplr.controlStyle=MPMovieControlModeHidden;

// mpmvplr.controlStyle=MPMovieControlModeVolumeOnly; // mpmvplr.controlStyle=MPMovieControlStyleFullscreen;

mpmvplr.repeatMode=MPMovieRepeatModeOne; mpmvplr.backgroundView.backgroundColor=[UIColor blueColor];

*/

[mpmvplr play]; [mpmvplr pause];

[mpmvplr stop];

MPMoviePlayerViewController

#import <MediaPlayer/MediaPlayer.h>

MPMoviePlayerViewController *mpmvvwplr;

NSString *strflpath=[[NSBundle mainBundle]pathForResource:@”Panasonic_Econavi_AirConditioner 2014- KatrinaKaif” ofType:@”mp4″];

NSURL *url=[NSURL fileURLWithPath:strflpath];

mpmvvwplr=[[MPMoviePlayerViewController alloc]initWithContentURL:url];

[self presentMoviePlayerViewControllerAnimated:mpmvvwplr];
// [self presentViewController:mpmvplr animated:YES completion:nil];

UIPickerView

<UIPickerViewDelegate,UIPickerViewDataSource>

NSMutableArray *arr1;

arr1=[[NSMutableArray alloc]initWithObjects:@”red”,@”green”,@”blue”,@”yellow” ,nil];

– (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;

{
return [arr1 count];

}

– (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;

{

return [arr1 objectAtIndex:row]; }

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{
if (row==0) {

self.view.backgroundColor=[UIColor redColor]; }

else if (row==1) {

self.view.backgroundColor=[UIColor greenColor]; }

else if (row==2) {

self.view.backgroundColor=[UIColor blueColor]; }

else if (row==3) {

self.view.backgroundColor=[UIColor yellowColor]; }

}

picker view through button click

– (IBAction)btnup:(id)sender {
int i =[pkervw selectedRowInComponent:0];
[pkervw selectRow:(i+1) inComponent:0 animated:YES];

[self pickerView:pkervw didSelectRow:i+1 inComponent:0]; }

– (IBAction)btndwn:(id)sender {
int i =[pkervw selectedRowInComponent:0];
[pkervw selectRow:(i-1) inComponent:0 animated:YES]; [self pickerView:pkervw didSelectRow:i-1 inComponent:0];

}

UICollectionView

<UICollectionViewDelegate,UICollectionViewDataSource>

delegate & datasource

NSMutableArray *arr1;

arr1 = [NSArray arrayWithObjects:@”angry_birds_cake.jpg”, @”creme_brelee.jpg”, @”egg_benedict.jpg”, @”full_breakfast.jpg”, @”green_tea.jpg”, @”ham_and_cheese_panini.jpg”, @”ham_and_egg_sandwich.jpg”, @”hamburger.jpg”, @”instant_noodle_with_egg.jpg”, @”japanese_noodle_with_pork.jpg”, @”mushroom_risotto.jpg”, @”noodle_with_bbq_pork.jpg”, @”starbucks_coffee.jpg”, @”thai_shrimp_cake.jpg”, @”vegetable_curry.jpg”, @”white_chocolate_donut.jpg”, nil];

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

return arr1.count; }

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

static NSString *striden=@”cell”;

UICollectionViewCell *cell1=[collectionView dequeueReusableCellWithReuseIdentifier:striden forIndexPath:indexPath];

UIImageView *imgvwrecp=(UIImageView *)[cell1 viewWithTag:11];

imgvwrecp.image=[UIImage imageNamed:[arr1 objectAtIndex:indexPath.row]];

cell1.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”photo-frame.png”]];

return cell1; }

UIScrollView Scrollimage through button

<UIScrollViewDelegate> NSMutableArray *arr1;

IBOutlet UIScrollView *scrlvw;

UIImageView *imgv; scrvw.delegate=self;

arr1=[[NSMutableArray alloc]initWithObjects:@”GRE_Interior13″,@”beach”,@”mountain”,@”prakruti “,@”sea”, nil];

[scrlvw setContentSize:CGSizeMake(320*[arr1 count], 548)]; for (int i=0; i<[arr1 count]; i++) {

imgv=[[UIImageView alloc]init];

imgv.frame=CGRectMake(320*i, 0, 320, 548);

NSString *str1=[arr1 objectAtIndex:i];

imgv.image=[UIImage imageNamed:[NSString stringWithFormat:@”%@.jpg”,str1]];

[scrlvw addSubview:imgv]; }

btnnxt

[scrlvw scrollRectToVisible:CGRectMake(scrlvw.contentOffset.x+50, scrlvw.contentOffset.y, scrlvw.frame.size.width, scrlvw.frame.size.height) animated:YES];

Btnpre

[scrlvw scrollRectToVisible:CGRectMake(scrlvw.contentOffset.x-50, scrlvw.contentOffset.y, scrlvw.frame.size.width, scrlvw.frame.size.height) animated:YES];

UIActionSheet

UIActionSheet *actns;

actns=[[UIActionSheet alloc]initWithTitle:@”select image” delegate:self cancelButtonTitle:@”cancle” destructiveButtonTitle:@”kinfo” otherButtonTitles:@”dance”,@”couple”,@”freedom”, nil];

[actns showInView:self.view];

– (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{
switch (buttonIndex) {

case 0:

self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@”kinfo.jpg”]];

break;

case 1:

self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@”dance.jpg”]];

break; case 2:

self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@”couple.jpg”]];

break; case 3:

self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@”freedom.jpg”]];

break;

case 4:
self.view.backgroundColor=[UIColor whiteColor];

break; default:

break; }

UITabBarController

AppDelegate.h @property(strong,nonatomic)UITabBarController *tbbar;

firstViewController *frst=[[firstViewController alloc]initWithNibName:@”firstViewController” bundle:nil];

frst.title=@”first”;

UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:frst];

secondViewController *secnd=[[secondViewController alloc]init]; secnd.title=@”second”;
self.tbbar=[[UITabBarController alloc]init]; self.tbbar.viewControllers=@[nav,secnd]; self.window.rootViewController=tbbar;

UITabBarController with UINavigationController

@property(strong,nonatomic)UITabBarController *tabbarctrl; onevc=[[oneViewController alloc]init];

onevc.title=@”onetab”;

UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:onevc];

twoViewController *two=[[twoViewController alloc]init]; two.title=@”twotab”;

threeViewController *three=[[threeViewController alloc]init]; three.title=@”threetab”;
tabbarctrl =[[UITabBarController alloc]init]; tabbarctrl.viewControllers=@[nav,two,three]; self.window.rootViewController=tabbarctrl;

UITabBarController

AppDelegate.h
@property(nonatomic,retain) UITabBarController *TabBarController; AppDelegate.m
#import “firstViewController.h”
#import “secondViewController.h” self.TabBarController=[[UITabBarController alloc]init];

firstViewController *first=[[firstViewController alloc]init];

first.title=@”honda civic”; //or below

first.tabBarItem.image=[UIImage imageNamed:@”honda-civic-in-india- 139542.png”];

secondViewController *second=[[secondViewController alloc]init];

second.title=@”i phone”; //or below

second.tabBarItem.image=[UIImage imageNamed:@”iphone-5-review- 1.png”];

self.TabBarController.viewControllers=[[NSArray alloc]initWithObjects:first,second, nil];

[[self. TabBarController.tabBar.items objectAtIndex:0] setTitle:@” honda civic “];

[[self. TabBarController.tabBar.items objectAtIndex:1]setTitle:@” i phone “];

[self.window setRootViewController:self.TabBarController];

Create Vcard File / Create .vcf

Contacts, NSDocumentDirectory

#import <Contacts/Contacts.h>

– (IBAction)btnCreatevcfFileClicked:(id)sender

{

    NSString *vcard = @”BEGIN:VCARDnVERSION:3.0n”;

    

    // Name

    vcard = [vcard stringByAppendingFormat:@”N:%@;%@;%@;%@;%@n”,

             @”lastname”, //lastname

             @”firstname”, //firstname

             @”middlename”, //middlename

             @”prefix”, //prefix

             @”suffix” //suffix

             ];

    

    vcard = [vcard stringByAppendingFormat:@”FN:%@n”,@”compositeName”]; //compositeName

    vcard = [vcard stringByAppendingFormat:@”NICKNAME:%@n”,@”nickname”]; //nickname

    vcard = [vcard stringByAppendingFormat:@”X-PHONETIC-FIRST-NAME:%@n”,@”firstnamephonetic”]; //firstnamephonetic

    vcard = [vcard stringByAppendingFormat:@”X-PHONETIC-LAST-NAME:%@n”,@”lastnamephonetic”]; //lastnamephonetic

    

    

    // Work

    vcard = [vcard stringByAppendingFormat:@”ORG:%@;%@n”,@”organization”,@”department”]; //organization, department

    vcard = [vcard stringByAppendingFormat:@”TITLE:%@n”,@”jobtitle”]; //jobtitle

    

    // Mail

    vcard = [self emailToVcardFieldEmail:@”email1@gmail.com” label:@”HOME” emailCounter:1 vCard:vcard]; //email, emailLabel

    vcard = [self emailToVcardFieldEmail:@”email2@gmail.com” label:@”WORK” emailCounter:2 vCard:vcard]; //email, emailLabel

    

    // Tel

    vcard = [self phoneToVcardFieldPhoneNo:@”1111111111″ label:@”MOBILE” phoneCounter:1 vCard:vcard]; //phone no, phoneLabel

    vcard = [self phoneToVcardFieldPhoneNo:@”2222222222″ label:@”MAIL” phoneCounter:2 vCard:vcard]; //phone no, phoneLabel

    vcard = [self phoneToVcardFieldPhoneNo:@”3333333333″ label:@”IPHONE” phoneCounter:3 vCard:vcard]; //phone no, phoneLabel

    vcard = [self phoneToVcardFieldPhoneNo:@”4444444444″ label:@”WORKFAX” phoneCounter:4 vCard:vcard]; //phone no, phoneLabel

    

    

   //  Adress

    NSDictionary *address1 = [[NSDictionary alloc]initWithObjectsAndKeys:

                             @”St Jhons”, @”Street”,

                             @”San Fransisco”, @”City”,

                             @”California”, @”State”,

                             @”27105″, @”ZIP”,

                             @”USA”, @”Country”,

                             @”1″, @”CountryCode”, nil];

    

    vcard = [self addressToVcardFieldAddress:address1 label:@”HOME” AddressCounter:1 vCard:vcard];

    

    NSDictionary *address2 = [[NSDictionary alloc]initWithObjectsAndKeys:

                             @”St Jhons”, @”Street”,

                             @”San Fransisco”, @”City”,

                             @”California”, @”State”,

                             @”27105″, @”ZIP”,

                             @”USA”, @”Country”,

                             @”1″, @”CountryCode”, nil];

     vcard = [self addressToVcardFieldAddress:address2 label:@”WORK” AddressCounter:2 vCard:vcard];

    

    // url

    vcard = [self urlToVcardFieldURL:@”www.apple.com” label:@”HOME” URLCounter:1 vCard:vcard]; //url, urlLabel

    vcard = [self urlToVcardFieldURL:@”www.google.com” label:@”WORK” URLCounter:2 vCard:vcard]; //url, urlLabel

    

    

    

    // IM SMS

    NSDictionary *im = [[NSDictionary alloc]initWithObjectsAndKeys:

                        @”Apple Service”, @”service”,

                        @”Apple User Name”, @”username”, nil];

    

    vcard = [self imToVcardFieldIm:im label:@”HOME” IMCounter:1 vCard:vcard]; //sms, smsLabel

    

    

    

    // birthday

    NSDate *birthday = @”1/1/2011″; //birthday

    if (birthday)

    {

        NSString *bday = [NSString stringWithFormat:@”%@”,birthday];

        NSArray *bdayArr = [bday componentsSeparatedByString:@” “];

        bday = [bdayArr objectAtIndex:0];

        

        vcard = [vcard stringByAppendingFormat:@”BDAY;value=date:%@n”,bday];

    }

    // Photo

    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@”Own_Selected”], 0.0);//imageData;

    if (imageData)

    {

        vcard = [vcard stringByAppendingFormat:@”PHOTO;BASE64:%@n”,[imageData base64Encoding]];

    }

    

    

    

    

    // end

    vcard = [vcard stringByAppendingString:@”END:VCARD”];

    

        NSLog(@”%@”,vcard);

    

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

        NSLog(@”%@”,documentsDirectory);

        NSError *error;

        BOOL succeed = [vcard writeToFile:[documentsDirectory stringByAppendingPathComponent:@”contact.vcf”]

                                      atomically:YES encoding:NSUTF8StringEncoding error:&error];

        if (!succeed){

            // Handle error here

            NSLog(@”Error”);

        }

    

    

    

    

    

}

– (NSString *)emailToVcardFieldEmail:(NSString *)email label:(NSString *)label emailCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    // label = Home

    // label = WORK

    

    NSString *labelLower = [label lowercaseString];

    

    

    if ([labelLower isEqualToString:@”_$!<home>!$_”]) vcard = [NSString stringWithFormat:@”EMAIL;type=INTERNET;type=HOME:%@n”,email];

    else if ([labelLower isEqualToString:@”_$!<work>!$_”]) vcard = [NSString stringWithFormat:@”EMAIL;type=INTERNET;type=WORK:%@n”,email];

    else

    {

        vcard = [vcard stringByAppendingFormat:@”item%d.EMAIL;type=INTERNET:%@nitem%d.X-ABLabel:%@n”,counter,email,counter,label];

    }

    return vcard;

}

– (NSString *)phoneToVcardFieldPhoneNo:(NSString *)phone label:(NSString *)label phoneCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    //MOBILE

    //IPHONE

    //HOME

    //WORK

    //MAIN

    //HOMEFAX

    //WORKFAX

    //PAGER

    

    

    

    NSString *labelLower = [label lowercaseString];

   

    

    if ([labelLower isEqualToString:@”_$!<mobile>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=CELL:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<iphone!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=IPHONE:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<home>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=HOME:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<work>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=WORK:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<main>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=MAIN:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<homefax>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=HOME;type=FAX:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<workfax>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=WORK;type=FAX:%@n”,phone];

    else if ([labelLower isEqualToString:@”_$!<pager>!$_”]) vcard = [NSString stringWithFormat:@”TEL;type=PAGER:%@n”,phone];

    else

    {

       //        if not showing phone number in outlook express in window use below code

//        vcard = [vcard stringByAppendingFormat:@”TEL;TYPE=%@,VOICE:%@n”,label,phone];

        vcard = [vcard stringByAppendingFormat:@”item%d.TEL:%@nitem%d.X-ABLabel:%@n”,counter,phone,counter,label];

        

    }

    

    return vcard;

}

– (NSString *)addressToVcardFieldAddress:(NSDictionary *)address label:(NSString *)label AddressCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    //WORK

    //HOME

    

    NSString *labelField = @””;

    NSString *labelLower = [label lowercaseString];

    NSString *type = @”HOME”;

    

    //

    if([labelLower isEqualToString:@”_$!<work>!$_”]) type = @”WORK”;

    else if([labelLower isEqualToString:@”_$!<home>!$_”]) {}

    else if( label && [label length] > 0 )

    {

        labelField = [NSString stringWithFormat:@”item%d.X-ABLabel:%@n”,counter,label];

    }

    

    //

    NSString *street = [address objectForKey:@”Street”] ? [address objectForKey:@”Street”] : @””;

    if ([street rangeOfString:@”n”].location != NSNotFound)

    {

        NSArray *arr = [street componentsSeparatedByString:@”n”];

        street = [arr componentsJoinedByString:@”n”];

    }

    

    NSString *City = [address objectForKey:@”City”] ? [address objectForKey:@”City”] : @””;

    NSString *State = [address objectForKey:@”State”] ? [address objectForKey:@”State”] : @””;

    NSString *ZIP = [address objectForKey:@”ZIP”] ? [address objectForKey:@”ZIP”] : @””;

    NSString *Country = [address objectForKey:@”Country”] ? [address objectForKey:@”Country”] : @””;

    NSString *CountryCode = [address objectForKey:@”CountryCode”] ? [address objectForKey:@”CountryCode”] : @””;

    

    

    //

    vcard = [vcard stringByAppendingFormat:@”item%d.ADR;type=%@:;;%@;%@;%@;%@;%@n%@item%d.X-ABADR:%@n”,

             counter,

             type,

             street,

             City,

             State,

             ZIP,

             Country,

             labelField,

             counter,

             CountryCode

             ];

    

    //

   

    return vcard;

}

– (NSString *)urlToVcardFieldURL:(NSString *)url label:(NSString *)label URLCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    //HOME

    //WORK

    

    NSString *labelLower = [label lowercaseString];

    

    if ([labelLower isEqualToString:@”_$!<home>!$_”]) vcard = [NSString stringWithFormat:@”URL;type=HOME:%@n”,url];

    else if ([labelLower isEqualToString:@”_$!<work>!$_”]) vcard = [NSString stringWithFormat:@”URL;type=WORK:%@n”,url];

    else

    {

        

        vcard = [vcard stringByAppendingFormat:@”item%d.URL:%@nitem%d.X-ABLabel:%@n”,counter,url,counter,label];

    }

    

    return vcard;

}

– (NSString *)imToVcardFieldIm:(NSDictionary *)im label:(NSString *)label IMCounter:(NSInteger)counter vCard:(NSString*)vcard

{

    

    //HOME

    //WORK

    

    

    NSString *labelLower = [label lowercaseString];

    

    NSString *service = [im objectForKey:@”service”] ? [im objectForKey:@”service”] : @””;

    service = [service uppercaseString];

    

    NSString *username = [im objectForKey:@”username”] ? [im objectForKey:@”username”] : @””;

    

    //

    if ([labelLower isEqualToString:@”_$!<home>!$_”] || [labelLower isEqualToString:@”_$!<work>!$_”])

    {

        NSString *type = [labelLower isEqualToString:@”_$!<home>!$_”] ? @”HOME” : @”WORK”;

        vcard = [NSString stringWithFormat:@”X-%@;type=%@:%@n”,service,type,username];

    }

    

    else

    {

        vcard = [vcard stringByAppendingFormat:@”item%d.X-%@:%@nitem%d.X-ABLabel:%@n”,counter,service,username,counter,label];

    }

    

    return vcard;

}

Attributed Label, Set html text on label

UILabel

    NSString * htmlString = @”<html><body>Apple is <b>great</b> <u>company</u> in USA</body></html>”;

    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

    

    [attrStr addAttribute:NSForegroundColorAttributeName

                 value:[UIColor redColor]

                 range:NSMakeRange([attrStr length]-3, 3)];

    

    self.labelFirst.attributedText = attrStr;

Singleton Method, Using singleton method concatenate two String

Singleton Method, NSString

ViewController.h

#import “SingletonClass.h”

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *stringFirst = @”First”;

    NSString *stringSecond = @”Second”;

    NSString *stringConcatenated;

    stringConcatenated = [[SingletonClass sharedSingletonClass]twoStringConcatenationFirstString:stringFirst SeconString:stringSecond];

    NSLog(@”%@”,stringConcatenated);

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

SingletonClass.h

+ (SingletonClass *)sharedSingletonClass;

– (NSString *)twoStringConcatenationFirstString:(NSString *)aFirstString SeconString:(NSString *)aSecondString;

SingletonClass.m

+ (SingletonClass *)sharedSingletonClass

{

    static SingletonClass *sharedInstance = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^

                  {

                      sharedInstance = [[self alloc]init];

                  });

    return sharedInstance;

}

– (NSString *)twoStringConcatenationFirstString:(NSString *)aFirstString SeconString:(NSString *)aSecondString

{

    NSString *strinfConcatenation;

    strinfConcatenation = [aFirstString stringByAppendingString:aSecondString];

    return strinfConcatenation;

}

Click here to download Singleton Method, Using singleton method concatenate two String Project

Bridging beetween Swift and Objective C

Swift

Bridging beetween Swift and Objective C

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        self.swiftFunction()

        print(self.swiftFunctionWithReturnValue())

        self.swiftFunctionPassingValueToObjectiveCClass()

        self.callOjectiveC()

        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        //Dispose of any resources that can be recreated.

    }

    

    func callOjectiveC()

    {

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        objClass.callASwiftFunction()

    }

    

    func  swiftFunction()

    {

        //Using objective c function here

        print(“Swift Class (__FUNCTION__)”)

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        objClass.objectiveCfunction()

    }

    

    func swiftFunctionWithReturnValue()->String

    {

        var returnValue:String;

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        let objCReturn:String = objClass.objectiveCFunctionWithReturnValue()

        returnValue = “Returning  from swiftFunctionWithReturnValue , appending (objCReturn) “

        return returnValue

    }

    

    func swiftFunctionPassingValueToObjectiveCClass()

    {

        let objClass:ObjectiveCClass =  ObjectiveCClass()

        objClass.objectiveCfunctionWithValuePassedFromSwiftClass(“Passing a string from Swift Class”);

    }

    

    func functionFromObjectiveC()

    {

        print(“In swift class , Function from objective c”);

    }

}

ObjectiveCClass.h

#import <Foundation/Foundation.h>

@interface ObjectiveCClass : NSObject

– (void)objectiveCfunction;

– (NSString *)objectiveCFunctionWithReturnValue;

– (void)objectiveCfunctionWithValuePassedFromSwiftClass:(NSString *)passedValue;

– (void)callASwiftFunction;

@end

ObjectiveCClass.m

#import “ObjectiveCClass.h”

#import “ObjectiveCSwiftBridging-Swift.h”

@implementation ObjectiveCClass

– (void)objectiveCfunction

{

    NSLog(@”Calling %s”,__func__);

}

– (NSString *)objectiveCFunctionWithReturnValue

{

    return @”Returning value from Objective C Class objectiveCFunctionWithReturnValue function”;

}

– (void)objectiveCfunctionWithValuePassedFromSwiftClass:(NSString *)passedValue

{

    NSLog(@”%@ and printed in objective c class %s”,passedValue,__func__);

}

– (void)callASwiftFunction

{

    ViewController *swiftViewcontroller = [[ViewController alloc] init];

    [swiftViewcontroller functionFromObjectiveC];

}

@end

Click here to download Bridging beetween Swift and Objective C Project

Custom Tableview, Click on table cell and Expand with another TableView, TableView Search

NSString, UIActivityIndicatorView, UITableView, typedef, NSArray, UIColor, CGFloat, NSDictionary, UISwitch, UIBezierPath, CAShapeLayer, Delegate, UIButton, UILabel, UIView, NSObject, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachable;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc] init];

    self.reachable = aReachable;

    self.reachable = [Reachability reachabilityWithHostName: @”apple.com”];

    [self.reachable startNotifier];

    

    return YES;

}

MCCallVendorsController.h

#import “ZJSwitch.h”

@interface MCCallVendorsController : UIViewController

@property (strong, nonatomic) NSString *moveTo;

@property  (strong, nonatomic) NSString *moveFrom;

@property (strong, nonatomic) NSArray *arrayJson;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

//@property (weak, nonatomic) IBOutlet UISwitch *switchMoveFromTo;

@property (weak, nonatomic) IBOutlet UIView *viewForSwitch;

MCCallVendorsController.m

#import “MCCallVendorsController.h”

#import “MCCallVendorVendorCell.h”

#import “MCCallVendorVendorModel.h”

#import “MCCallVendorTaskCell.h”

#import “MCCallVendorTaskModel.h”

#import “Utility.h”

//#import “MCNetworkManager.h”

#import “MCVendorsListController.h”

NSString *const filterTaskConstant = @”%K CONTAINS[c] %@”;

NSString *const vendorCell = @”vendorCell”;

NSString *const viewMore = @”viewMore”;

NSString *const taskSectionCell = @”taskSectionCell”;

NSString *const placeholderText = @”Search:moving, packing”;

NSString *const vendorsListControllerName = @”MCVendorsListController”;

typedef enum

{

    MCVendorTypeFrom,

    MCVendorTypeTo

}MCVendorType;

@interface MCCallVendorsController ()<UITableViewDataSource,UITableViewDelegate,MCCallVendorTaskCellProtocol , MCCallVendorVendorCellProtocol,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (nonatomic, strong) NSMutableArray *fromModelArray;

@property (nonatomic, strong) NSMutableArray *toModelArray;

@property (nonatomic, strong) NSArray *modelArray;

@property (nonatomic, assign) MCVendorType vendorType;

@property (weak, nonatomic) IBOutlet UITableView *taskVendorsTableView;

@end

@implementation MCCallVendorsController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    [self.activityIndicator startAnimating];

    self.navigationController.navigationBarHidden = YES;

    self.vendorType = MCVendorTypeFrom;

    [self loadModels];

    UIColor *color = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];

    self.searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

    

    

    CGFloat r1 = CGRectGetHeight(self.viewForSwitch.bounds) / 2.0;

    self.viewForSwitch.layer.cornerRadius = r1;

    

    ZJSwitch *switchMoveFromTo = [[ZJSwitch alloc] initWithFrame:CGRectMake(2, 2, self.viewForSwitch.frame.size.width4, self.viewForSwitch.frame.size.height4)];

    switchMoveFromTo.on = NO;

    switchMoveFromTo.backgroundColor = [UIColor clearColor];

    switchMoveFromTo.onTintColor = [UIColor colorWithRed:37/255.0 green:81/255.0 blue:92/255.0 alpha:1];

    switchMoveFromTo.offTintColor = [UIColor colorWithRed:37/255.0 green:81/255.0 blue:92/255.0 alpha:1];

    switchMoveFromTo.textColor = [UIColor blackColor];

    switchMoveFromTo.onText = @”Moving To”;

    switchMoveFromTo.offText = @”Moving From”;

    //switch2.textFont = @””;

    [switchMoveFromTo setOnTextFontSize:7];

    [switchMoveFromTo setOffTextFontSize:7];

    [switchMoveFromTo addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitch addSubview:switchMoveFromTo];

    

    // Do any additional setup after loading the view.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    

    //sample data

    

    // Dispose of any resources that can be recreated.

}

– (void)loadModels

{

    

    NSDictionary *dictionary = @{

                                 @”moveTo”: @”11111″,

                                 @”moveFrom”:@”22222″

                                 };

    

//    [[MCNetworkManager sharedNetworkManager] getVendorsList:dictionary withCompletionBlock:^(NSDictionary *response, NSError *error) {

//        NSLog(@”Response”);

//        NSArray *moveFromArray = response[@”result”][@”move_from”][@”tasks”];

//        NSArray *moveToArray = response[@”result”][@”move_to”][@”tasks”];

//        self.fromModelArray = [NSMutableArray array];

//        self.toModelArray = [NSMutableArray array];

//        [self generateVendorsModelsForArray:moveFromArray moveIntoArray:self.fromModelArray];

//        [self generateVendorsModelsForArray:moveToArray moveIntoArray:self.toModelArray];

//        self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

//        [self.taskVendorsTableView reloadData];

//        [self.activityIndicator stopAnimating];

//        self.activityIndicator.hidden = YES;

//    }];

    

    

    

    self.arrayJson = [Utility parseStatesResponseFileName:@”Json_File” FileType:@”json”];

    NSLog(@”%@”,self.arrayJson);

    

    NSDictionary *response = (NSDictionary *)self.arrayJson;

    

    NSArray *moveFromArray = response[@”result”][@”move_from”][@”tasks”];

            NSArray *moveToArray = response[@”result”][@”move_to”][@”tasks”];

            self.fromModelArray = [NSMutableArray array];

            self.toModelArray = [NSMutableArray array];

            [self generateVendorsModelsForArray:moveFromArray moveIntoArray:self.fromModelArray];

            [self generateVendorsModelsForArray:moveToArray moveIntoArray:self.toModelArray];

            self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

            [self.taskVendorsTableView reloadData];

            [self.activityIndicator stopAnimating];

            self.activityIndicator.hidden = YES;

}

     

     

– (void)generateVendorsModelsForArray:(NSArray *)array moveIntoArray:(NSMutableArray *)movingArray

{

         for(NSDictionary *taskWithVedorsList in array)

         {

             MCCallVendorTaskModel *model = [[MCCallVendorTaskModel alloc] init];

             //set task and vendors list details

             [model setDataFromDictionary:taskWithVedorsList];

             model.expanded = NO;

             [movingArray addObject:model];

         }

}

– (IBAction)switchStateChanged:(id)sender

{

    UISwitch *toFromswitch = (UISwitch *)sender;

    self.vendorType  = (toFromswitch.isOn) ? MCVendorTypeFrom : MCVendorTypeTo;

    [self filterTasks:self.searchTextField.text];

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    MCCallVendorTaskModel *taskModel = self.modelArray[section];

    NSInteger rows = (taskModel.expanded) ? ((taskModel.vendorsArray.count > 5) ? 6 : taskModel.vendorsArray.count) : 0;

    return rows;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *identifier = vendorCell;

    MCCallVendorTaskModel *model = self.modelArray[indexPath.section];

    NSArray *vendorsArray = model.vendorsArray;

    if(indexPath.row > 4 && vendorsArray.count > 5)

    {

        identifier = viewMore;

    }

    MCCallVendorVendorCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    cell.delegate = self;

    cell.section = indexPath.section;

    cell.model = vendorsArray[indexPath.row];

    

    if([identifier isEqualToString:vendorCell])

    {

        //check if last cell and vendor cell

        if((indexPath.row == vendorsArray.count1))

        {

            dispatch_async(dispatch_get_main_queue(), ^{

                UIBezierPath *maskPath;

                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                                 byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                       cornerRadii:CGSizeMake(5.0, 5.0)];

                

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

                maskLayer.path = maskPath.CGPath;

                maskLayer.frame = cell.bounds;

                cell.layer.mask = maskLayer;

                cell.separator.hidden = YES;

            });

        }

        else

        {

            dispatch_async(dispatch_get_main_queue(), ^{

                UIBezierPath *maskPath;

                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                                 byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                       cornerRadii:CGSizeMake(0.0, 0.0)];

                

                CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

                maskLayer.path = maskPath.CGPath;

                maskLayer.frame = cell.bounds;

                cell.layer.mask = maskLayer;

                if((indexPath.row > 3 && vendorsArray.count > 5))

                {

                    cell.separator.hidden = YES;

                }

                else

                {

                    cell.separator.hidden = NO;

                }

            });

        }

       

    }

    else if ([identifier isEqualToString:viewMore])

    {

        dispatch_async(dispatch_get_main_queue(), ^{

            UIBezierPath *maskPath;

            maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                             byRoundingCorners:(UIRectCornerBottomRight|UIRectCornerBottomLeft)

                                                   cornerRadii:CGSizeMake(5.0, 5.0)];

            

            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

            maskLayer.path = maskPath.CGPath;

            maskLayer.frame = cell.bounds;

            cell.layer.mask = maskLayer;

        });

    }

    

    return cell;

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return self.modelArray.count;

}

– (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{

    MCCallVendorTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:taskSectionCell];

    cell.delegate = self;

    cell.model = self.modelArray[section];

    dispatch_async(dispatch_get_main_queue(), ^{

        UIBezierPath *maskPath;

        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds

                                         byRoundingCorners:(UIRectCornerTopRight|UIRectCornerTopLeft)

                                               cornerRadii:CGSizeMake(5.0, 5.0)];

        

        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

        maskLayer.path = maskPath.CGPath;

        maskLayer.frame = cell.bounds;

        cell.layer.mask = maskLayer;

    });

    return cell;

}

– (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section

{

    return 20.0;

}

– (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section

{

    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];

    view.backgroundColor = [UIColor clearColor];

    return  view;

}

#pragma mark – Task cell delegates –

– (void)expandCell:(MCCallVendorTaskCell *)cell

{

    for(int i=0; i< self.modelArray.count ; i++)

    {

        MCCallVendorTaskModel *model = self.modelArray[i];

        if(model != cell.model)

        {

            model.expanded = NO;

        }

    }

    cell.model.expanded = !(cell.model.expanded);

    [self.taskVendorsTableView reloadData];

}

#pragma  mark – Vendor cell delegates –

– (void)tappedViewMore:(MCCallVendorVendorCell *)cell

{

    //push a new controller

    MCVendorsListController *vendorsListController = [[UIStoryboard storyboardWithName:vendorsListControllerName bundle:nil] instantiateInitialViewController];

    //pass the selected vendors list,this a a parcular vendor cell, but we need to get list of the vendors for that section

    vendorsListController.model = self.modelArray[cell.section];

    [self.navigationController pushViewController:vendorsListController animated:YES];

}

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell

{

    //call the vendor

    [Utility makeCall:cell.model.vendorPhone];

}

– (IBAction)searchTasks:(id)sender

{

    NSString *textToSearch = ((UITextField *)sender).text ;

    [self filterTasks:textToSearch];

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    [self.view endEditing:YES];

    return YES;

}

– (void)filterTasks:(NSString *)filterText

{

    NSLog(@”%@”,filterText);

    if(filterText.length)

    {

        NSArray *taskVendorArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

        NSString* filter =  filterTaskConstant;

        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, @”taskName”,filterText];

        NSArray* filteredData = [taskVendorArray filteredArrayUsingPredicate:predicate];

        //filtered Data

        self.modelArray = filteredData;

        NSLog(@”Filtered Data”);

        [self.taskVendorsTableView reloadData];

    }

    else

    {

        self.modelArray = (self.vendorType == MCVendorTypeFrom) ? self.fromModelArray : self.toModelArray;

        [self.taskVendorsTableView reloadData];

    }

}

– (IBAction)tapGesture:(id)sender

{

    [self.view endEditing:YES];

}

MCCallVendorTaskCell.h

#import <UIKit/UIKit.h>

#import “MCCallVendorTaskModel.h”

@class MCCallVendorTaskCell;

@protocol MCCallVendorTaskCellProtocol <NSObject>

– (void)expandCell:(MCCallVendorTaskCell *)cell;

@end

@interface MCCallVendorTaskCell : UITableViewCell

@property (nonatomic, strong) MCCallVendorTaskModel *model;

@property (nonatomic, assign) id <MCCallVendorTaskCellProtocol> delegate;

@end

MCCallVendorTaskCell.m

#import “MCCallVendorTaskCell.h”

@interface MCCallVendorTaskCell()

@property (weak, nonatomic) IBOutlet UILabel *taskName;

@property (weak, nonatomic) IBOutlet UIButton *expandButton;

@end

@implementation MCCallVendorTaskCell

– (IBAction)expandButtonAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(expandCell:)])

    {

        [self.delegate expandCell:self];

        [self updateButtonState];

    }

}

– (void)setModel:(MCCallVendorTaskModel *)model

{

    _model = model;

    self.taskName.text = _model.taskName;

    [self updateButtonState];

}

– (void)updateButtonState

{

    if(self.model.expanded)

    {

        [self.expandButton setBackgroundImage:[UIImage imageNamed:@”drop-up”] forState:UIControlStateNormal];

    }

    else

    {

        [self.expandButton setBackgroundImage:[UIImage imageNamed:@”drop-down”] forState:UIControlStateNormal];

    }

}

@end

MCCallVendorTaskModel.h

#import <Foundation/Foundation.h>

#import “MCCallVendorVendorModel.h”

@interface MCCallVendorTaskModel : NSObject

@property (nonatomic, assign) BOOL expanded;

@property (nonatomic, strong) NSString *taskName;

@property (nonatomic, strong) NSMutableArray *vendorsArray; // of type vendors model

– (void)setDataFromDictionary:(NSDictionary *)dictionary;

@end

MCCallVendorTaskModel.m

#import “MCCallVendorTaskModel.h”

@implementation MCCallVendorTaskModel

– (void)setDataFromDictionary:(NSDictionary *)dictionary

{

    self.taskName = dictionary[@”name”];

    //vendors

    self.vendorsArray = [NSMutableArray array];

    NSArray *vendorsArray = dictionary[@”vendors”];

    for(NSDictionary *vendorDictionay in vendorsArray )

    {

        MCCallVendorVendorModel *vendorModel = [[MCCallVendorVendorModel alloc] init];

        [vendorModel setDataFromDictionary:vendorDictionay];

        [self.vendorsArray addObject:vendorModel];

    }

}

@end

MCCallVendorVendorCell.h

#import <UIKit/UIKit.h>

#import “MCCallVendorVendorModel.h”

@class MCCallVendorVendorCell;

@protocol MCCallVendorVendorCellProtocol <NSObject>

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell;

@optional

– (void)tappedViewMore:(MCCallVendorVendorCell *)cell;

@end

@interface MCCallVendorVendorCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIView *separator;

@property (nonatomic, weak) id <MCCallVendorVendorCellProtocol> delegate;

@property (nonatomic, strong) MCCallVendorVendorModel *model;

@property (nonatomic, assign) NSUInteger section;

@end

MCCallVendorVendorCell.m

#import “MCCallVendorVendorCell.h”

@interface MCCallVendorVendorCell ()

@property (weak, nonatomic) IBOutlet UILabel *vendorName;

@end

@implementation MCCallVendorVendorCell

– (void)setModel:(MCCallVendorVendorModel *)model

{

    _model = model;

    self.vendorName.text = _model.vendorName;

}

– (IBAction)callVendorAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(tappedCallVendor:)])

    {

        [self.delegate tappedCallVendor:self];

    }

}

– (IBAction)viewMoreAction:(id)sender

{

    if(self.delegate && [self.delegate respondsToSelector:@selector(tappedViewMore:)])

    {

        [self.delegate tappedViewMore:self];

    }

}

@end

MCCallVendorVendorModel.h

#import <Foundation/Foundation.h>

@interface MCCallVendorVendorModel : NSObject

@property (nonatomic, strong) NSString *vendorName;

@property (nonatomic, strong) NSString *vendorPhone;

– (void)setDataFromDictionary:(NSDictionary *)dictionary;

@end

MCCallVendorVendorModel.m

#import “MCCallVendorVendorModel.h”

@implementation MCCallVendorVendorModel

– (void)setDataFromDictionary:(NSDictionary *)dictionary

{

    self.vendorName = dictionary[@”name”];

    self.vendorPhone = dictionary[@”phone”];

}

@end

MCVendorsListController.h

#import <UIKit/UIKit.h>

#import “MCCallVendorTaskModel.h”

@interface MCVendorsListController : UIViewController

@property (nonatomic, strong) MCCallVendorTaskModel *model; // task model with name and list of vendors

@end

MCVendorsListController.m

#import “MCVendorsListController.h”

#import “MCCallVendorVendorCell.h”

#import “Utility.h”

NSString *const vendorsFilterString =  @”%K CONTAINS[c] %@”;

NSString *const vendorCellIdentifier = @”vendorCell”;

@interface MCVendorsListController()<UITableViewDataSource, UITableViewDelegate , MCCallVendorVendorCellProtocol>

@property (weak, nonatomic) IBOutlet UITableView *vendorsTableView;

@property (nonatomic, strong) NSArray *modelsArray;

@end

@implementation MCVendorsListController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.navigationController.navigationBarHidden = YES;

    [self loadAllVendors];

}

– (void)loadAllVendors

{

    self.modelsArray = self.model.vendorsArray;

    [self.vendorsTableView reloadData];

}

– (IBAction)backButtonAction:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.modelsArray.count;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    MCCallVendorVendorCell *cell = [tableView dequeueReusableCellWithIdentifier:vendorCellIdentifier];

    cell.model = self.modelsArray[indexPath.row];

    cell.delegate = self;

    return cell;

}

– (IBAction)searchVendors:(id)sender

{

    NSString *textToSearch = ((UITextField *)sender).text ;

    NSLog(@”%@”,textToSearch);

    if(textToSearch.length)

    {

        NSArray *taskVendorArray = self.model.vendorsArray;

        NSString* filter = vendorsFilterString;

        NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, @”vendorName”,textToSearch];

        NSArray* filteredData = [taskVendorArray filteredArrayUsingPredicate:predicate];

        //filtered Data

        self.modelsArray = filteredData;

        NSLog(@”Filtered Data”);

        [self.vendorsTableView reloadData];

    }

    else

    {

        self.modelsArray = self.model.vendorsArray;

        [self.vendorsTableView reloadData];

    }

}

#pragma mark – vendor cell delegates –

– (void)tappedCallVendor:(MCCallVendorVendorCell *)cell

{

    [Utility makeCall:cell.model.vendorPhone];

}

@end

Click here to download Custom Tableview, Click on table cell and Expand with another TableView, TableView Search Project

Custom Switch ,Change switch name

UISwitch, UIFont, UIColor, UILabel, NSString, UIGestureRecognizer, 

ViewController.h

#import “ZJSwitch.h”

@property (weak, nonatomic) IBOutlet UIView *viewForSwitchFirst;

@property (weak, nonatomic) IBOutlet UIView *viewForSwitchTwo;

@property (weak, nonatomic) IBOutlet UISwitch *SwitchOnOff;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

//    self.SwitchOnOff.onImage = [UIImage imageNamed:@”toggle-from.png”];

//    self.SwitchOnOff.offImage = [UIImage imageNamed:@”toggle-to.png”];

    

    

    CGFloat r1 = CGRectGetHeight(self.viewForSwitchFirst.bounds) / 2.0;

    self.viewForSwitchFirst.layer.cornerRadius = r1;

    

    ZJSwitch *switch1 = [[ZJSwitch alloc] initWithFrame:CGRectMake(5, 5, self.viewForSwitchFirst.frame.size.width10, self.viewForSwitchFirst.frame.size.height10)];

    switch1.on = YES;

    switch1.backgroundColor = [UIColor clearColor];

    switch1.onTintColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:255/255.0 alpha:1];

    switch1.offTintColor = [UIColor colorWithRed:0/255.0 green:255/255.0 blue:0/255.0 alpha:1];

    switch1.textColor = [UIColor blackColor];

    switch1.onText = @”Switch ON”;

    switch1.offText = @”Switch OFF”;

    //switch2.textFont = @””;

    [switch1 setOnTextFontSize:10];

    [switch1 setOffTextFontSize:10];

    [switch1 addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitchFirst addSubview:switch1];

    

    

    CGFloat r2 = CGRectGetHeight(self.viewForSwitchTwo.bounds) / 2.0;

    self.viewForSwitchTwo.layer.cornerRadius = r2;

    

    ZJSwitch *switch2 = [[ZJSwitch alloc] initWithFrame:CGRectMake(5, 5, self.viewForSwitchTwo.frame.size.width10, self.viewForSwitchTwo.frame.size.height10)];

    switch2.on = YES;

    switch2.backgroundColor = [UIColor clearColor];

    switch2.tintColor = [UIColor orangeColor];

    [switch2 addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];

    [self.viewForSwitchTwo addSubview:switch2];

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)switchActionOnOff:(id)sender

{

    NSLog(@”%@”,sender);

    

    if ([self.SwitchOnOff isOn])

    {

        NSLog(@”Switch id On”);

    }

    else

    {

        NSLog(@”Switch is Off”);

    }

}

– (void)handleSwitchEvent:(id)sender

{

    if ([sender isOn])

    {

        NSLog(@”Switch is On”);

    }

    else

    {

        NSLog(@”Switch is Off”);

    }

}

ZJSwitch.h

#import <UIKit/UIKit.h>

@interface ZJSwitch : UIControl

@property (nonatomic, assign, getter = isOn) BOOL on;

@property (nonatomic, strong) UIColor *onTintColor;

@property (nonatomic, strong) UIColor *offTintColor;

@property (nonatomic, strong) UIColor *thumbTintColor;

@property (nonatomic, strong) UIColor *textColor;

@property (nonatomic, strong) UIFont *textFont;

@property (nonatomic, strong) NSString *onText;

@property (nonatomic, strong) NSString *offText;

– (void)setTextFont:(UIFont *)textFont;

– (void)setOnTextFontSize:(CGFloat)onTextFontSize;

– (void)setOffTextFontSize:(CGFloat)offTextFontSize;

– (void)setOn:(BOOL)on animated:(BOOL)animated;

ZJSwitch.m

#import “ZJSwitch.h”

#define ZJSwitchMaxHeight 100.0f

#define ZJSwitchMinHeight 20.0f

#define ZJSwitchMinWidth 30.0f

#define ZJSwitchKnobSize 15.0f

@interface ZJSwitch ()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UIView *onContentView;

@property (nonatomic, strong) UIView *offContentView;

@property (nonatomic, strong) UIView *knobView;

@property (nonatomic, strong) UILabel *onLabel;

@property (nonatomic, strong) UILabel *offLabel;

– (void)commonInit;

– (CGRect)roundRect:(CGRect)frameOrBounds;

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer;

– (void)handlePanGestureRecognizerEvent:(UIPanGestureRecognizer *)recognizer;

@end

@implementation ZJSwitch

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:[self roundRect:frame]];

    if (self) {

        [self commonInit];

    }

    return self;

}

– (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super initWithCoder:aDecoder];

    

    if (self) {

        [self commonInit];

    }

    

    return self;

}

– (void)setBounds:(CGRect)bounds

{

    [super setBounds:[self roundRect:bounds]];

    

    [self setNeedsLayout];

}

– (void)setFrame:(CGRect)frame

{

    [super setFrame:[self roundRect:frame]];

    

    [self setNeedsLayout];

}

– (void)setTextFont:(UIFont *)textFont

{

    _onLabel.font = textFont;

    _offLabel.font = textFont;

    

}

– (void)setOnText:(NSString *)onText

{

    if (_onText != onText) {

        _onText = onText;

        

        _onLabel.text = onText;

    }

}

– (void)setOffText:(NSString *)offText

{

    if (_offText != offText) {

        _offText = offText;

        

        _offLabel.text = offText;

    }

}

– (void)setOnTextFontSize:(CGFloat)onTextFontSize

{

    [_onLabel setFont:[UIFont systemFontOfSize:onTextFontSize]];

    

}

– (void)setOffTextFontSize:(CGFloat)offTextFontSize

{

     [_offLabel setFont:[UIFont systemFontOfSize:offTextFontSize]];

}

– (void)setOnTintColor:(UIColor *)onTintColor

{

    if (_onTintColor != onTintColor) {

        _onTintColor = onTintColor;

        

        _onContentView.backgroundColor = onTintColor;

    }

}

– (void)setOffTintColor:(UIColor *)offTintColor

{

    if (_offTintColor != offTintColor) {

        _offTintColor = offTintColor;

        

        _offContentView.backgroundColor = offTintColor;

    }

}

– (void)setThumbTintColor:(UIColor *)thumbTintColor

{

    if (_thumbTintColor != thumbTintColor) {

        _thumbTintColor = thumbTintColor;

        

        _knobView.backgroundColor = _thumbTintColor;

    }

}

– (void)layoutSubviews

{

    [super layoutSubviews];

    

    self.containerView.frame = self.bounds;

    

    CGFloat r = CGRectGetHeight(self.containerView.bounds) / 2.0;

    

    self.containerView.layer.cornerRadius = r;

    self.containerView.layer.masksToBounds = YES;

    

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    

    if (!self.isOn) {

        // frame of off status

        self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                              0,

                                              CGRectGetWidth(self.containerView.bounds),

                                              CGRectGetHeight(self.containerView.bounds));

        

        self.offContentView.frame = CGRectMake(0,

                                               0,

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetHeight(self.containerView.bounds));

        

        self.knobView.frame = CGRectMake(margin,

                                         margin,

                                         ZJSwitchKnobSize,

                                         ZJSwitchKnobSize);

    } else {

        // frame of on status

        self.onContentView.frame = CGRectMake(0,

                                              0,

                                              CGRectGetWidth(self.containerView.bounds),

                                              CGRectGetHeight(self.containerView.bounds));

        

        self.offContentView.frame = CGRectMake(0,

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetWidth(self.containerView.bounds),

                                               CGRectGetHeight(self.containerView.bounds));

        

        self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                         margin,

                                         ZJSwitchKnobSize,

                                         ZJSwitchKnobSize);

    }

    

    CGFloat lHeight = 20.0f;

    CGFloat lMargin = r – (sqrtf(powf(r, 2) – powf(lHeight / 2.0, 2))) + margin;

    

    self.onLabel.frame = CGRectMake(lMargin,

                                    r – lHeight / 2.0,

                                    CGRectGetWidth(self.onContentView.bounds) – lMargin – ZJSwitchKnobSize2 * margin,

                                    lHeight);

    

    self.offLabel.frame = CGRectMake(ZJSwitchKnobSize + 2 * margin,

                                     r – lHeight / 2.0,

                                     CGRectGetWidth(self.onContentView.bounds) – lMargin – ZJSwitchKnobSize2 * margin,

                                     lHeight);

}

– (void)setOn:(BOOL)on

{

    [self setOn:on animated:NO];

}

– (void)setOn:(BOOL)on animated:(BOOL)animated

{

    if (_on == on) {

        return;

    }

    

    _on = on;

    

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    

    if (!animated) {

        if (!self.isOn) {

            // frame of off status

            self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                                  0,

                                                  CGRectGetWidth(self.containerView.bounds),

                                                  CGRectGetHeight(self.containerView.bounds));

            

            self.offContentView.frame = CGRectMake(0,

                                                   0,

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetHeight(self.containerView.bounds));

            

            self.knobView.frame = CGRectMake(margin,

                                             margin,

                                             ZJSwitchKnobSize,

                                             ZJSwitchKnobSize);

        } else {

            // frame of on status

            self.onContentView.frame = CGRectMake(0,

                                                  0,

                                                  CGRectGetWidth(self.containerView.bounds),

                                                  CGRectGetHeight(self.containerView.bounds));

            

            self.offContentView.frame = CGRectMake(0,

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetWidth(self.containerView.bounds),

                                                   CGRectGetHeight(self.containerView.bounds));

            

            self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                             margin,

                                             ZJSwitchKnobSize,

                                             ZJSwitchKnobSize);

        }

    } else {

        if (self.isOn) {

            [UIView animateWithDuration:0.25

                             animations:^{

                                 self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – ZJSwitchKnobSize,

                                                                  margin,

                                                                  ZJSwitchKnobSize,

                                                                  ZJSwitchKnobSize);

                             }

                             completion:^(BOOL finished){

                                 self.onContentView.frame = CGRectMake(0,

                                                                       0,

                                                                       CGRectGetWidth(self.containerView.bounds),

                                                                       CGRectGetHeight(self.containerView.bounds));

                                 

                                 self.offContentView.frame = CGRectMake(0,

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetHeight(self.containerView.bounds));

                             }];

        } else {

            [UIView animateWithDuration:0.25

                             animations:^{

                                 self.knobView.frame = CGRectMake(margin,

                                                                  margin,

                                                                  ZJSwitchKnobSize,

                                                                  ZJSwitchKnobSize);

                             }

                             completion:^(BOOL finished){

                                 self.onContentView.frame = CGRectMake(-1 * CGRectGetWidth(self.containerView.bounds),

                                                                       0,

                                                                       CGRectGetWidth(self.containerView.bounds),

                                                                       CGRectGetHeight(self.containerView.bounds));

                                 

                                 self.offContentView.frame = CGRectMake(0,

                                                                        0,

                                                                        CGRectGetWidth(self.containerView.bounds),

                                                                        CGRectGetHeight(self.containerView.bounds));

                             }];

        }

    }

    

    [self sendActionsForControlEvents:UIControlEventValueChanged];

}

#pragma mark – Private API

– (void)commonInit

{

    self.backgroundColor = [UIColor clearColor];

    

    _onTintColor = [UIColor colorWithRed:130 / 255.0 green:200 / 255.0 blue:90 / 255.0 alpha:1.0];

    _offTintColor = [UIColor colorWithWhite:0.75 alpha:1.0];

    _thumbTintColor = [UIColor colorWithWhite:1.0 alpha:1.0];

    

    _textFont = [UIFont systemFontOfSize:10.0f];

    _textColor = [UIColor whiteColor];

    

    _containerView = [[UIView alloc] initWithFrame:self.bounds];

    _containerView.backgroundColor = [UIColor clearColor];

    [self addSubview:_containerView];

    

    _onContentView = [[UIView alloc] initWithFrame:self.bounds];

    _onContentView.backgroundColor = _onTintColor;

    [_containerView addSubview:_onContentView];

    

    _offContentView = [[UIView alloc] initWithFrame:self.bounds];

    _offContentView.backgroundColor = _offTintColor;

    [_containerView addSubview:_offContentView];

    

    _knobView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZJSwitchKnobSize, ZJSwitchKnobSize)];

    _knobView.backgroundColor = _thumbTintColor;

    _knobView.layer.cornerRadius = (ZJSwitchKnobSize / 2.0);

    [_containerView addSubview:_knobView];

    

    _onLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    _onLabel.backgroundColor = [UIColor clearColor];

    _onLabel.textAlignment = NSTextAlignmentCenter;

    _onLabel.textColor = _textColor;

    _onLabel.font = _textFont;

    _onLabel.text = _onText;

    [_onContentView addSubview:_onLabel];

    

    _offLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    _offLabel.backgroundColor = [UIColor clearColor];

    _offLabel.textAlignment = NSTextAlignmentCenter;

    _offLabel.textColor = _textColor;

    _offLabel.font = _textFont;

    _offLabel.text = _offText;

    [_offContentView addSubview:_offLabel];

    

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handleTapTapGestureRecognizerEvent:)];

    [self addGestureRecognizer:tapGesture];

    

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self

                                                                                 action:@selector(handlePanGestureRecognizerEvent:)];

    [self addGestureRecognizer:panGesture];

}

– (CGRect)roundRect:(CGRect)frameOrBounds

{

    CGRect newRect = frameOrBounds;

    

    if (newRect.size.height > ZJSwitchMaxHeight) {

        newRect.size.height = ZJSwitchMaxHeight;

    }

    

    if (newRect.size.height < ZJSwitchMinHeight) {

        newRect.size.height = ZJSwitchMinHeight;

    }

    

    if (newRect.size.width < ZJSwitchMinWidth) {

        newRect.size.width = ZJSwitchMinWidth;

    }

    

    return newRect;

}

– (void)handleTapTapGestureRecognizerEvent:(UITapGestureRecognizer *)recognizer

{

    if (recognizer.state == UIGestureRecognizerStateEnded) {

        [self setOn:!self.isOn animated:NO];

    }

}

– (void)handlePanGestureRecognizerEvent:(UIPanGestureRecognizer *)recognizer

{

    CGFloat margin = (CGRectGetHeight(self.bounds) – ZJSwitchKnobSize) / 2.0;

    CGFloat offset = 6.0f;

    

    switch (recognizer.state) {

        case UIGestureRecognizerStateBegan:{

            if (!self.isOn) {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(margin,

                                                                      margin,

                                                                      ZJSwitchKnobSize + offset,

                                                                      ZJSwitchKnobSize);

                                 }];

            } else {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – margin – (ZJSwitchKnobSize + offset),

                                                                      margin,

                                                                      ZJSwitchKnobSize + offset,

                                                                      ZJSwitchKnobSize);

                                 }];

            }

            break;

        }

        case UIGestureRecognizerStateCancelled:

        case UIGestureRecognizerStateFailed: {

            if (!self.isOn) {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(margin,

                                                                      margin,

                                                                      ZJSwitchKnobSize,

                                                                      ZJSwitchKnobSize);

                                 }];

            } else {

                [UIView animateWithDuration:0.25

                                 animations:^{

                                     self.knobView.frame = CGRectMake(CGRectGetWidth(self.containerView.bounds) – ZJSwitchKnobSize,

                                                                      margin,

                                                                      ZJSwitchKnobSize,

                                                                      ZJSwitchKnobSize);

                                 }];

            }

            break;

        }

        case UIGestureRecognizerStateChanged:{

            break;

        }

        case UIGestureRecognizerStateEnded:

            [self setOn:!self.isOn animated:YES];

            break;

        case UIGestureRecognizerStatePossible:

            break;

    }

}

Click here to download Custom Switch ,Change switch name Project

 

Image Downloading show in ProgressView

NSURL, UIImageView, UIImage, UIProgressView, NSURLSession

ViewController.h

<NSURLSessionDelegate, NSURLSessionDownloadDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@”https://i.ytimg.com/vi/QGiJFumHUPo/maxresdefault.jpg&#8221;]];

    [downloadTask resume];

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {

    NSData *data = [NSData dataWithContentsOfURL:location];

    

    dispatch_async(dispatch_get_main_queue(), ^{

        //[self.progressView setHidden:YES];

        [self.imageView setImage:[UIImage imageWithData:data]];

    });

}

– (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

    

}

– (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {

    float progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;

    

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.progressView setProgress:progress];

    });

}

Click here to download Image Downloading show in ProgressView Project

Check self.navigationController.viewControllers has MCHomeScreenViewController ViewController or not, Set delegate of previous Viewcontroller

Custom Delegate, Delegate, UINavigationController

NSLog(@”%@”,self.navigationController.viewControllers);

        

NSLog(@”%ld”,(long)self.navigationController.viewControllers.count);

UserProfileVC *upf = [[UserProfileVC alloc]initWithNibName:@”UserProfileVC” bundle:nil];

        if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count2]  isKindOfClass:[MCHomeScreenViewController class]])

        {

            NSLog(@”%@”,[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count2]);

            upf.delegate = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count2];

        }

        else

        {

            upf.delegate = nil;

        }

        

        

        upf.profiledic = prodic;

        

        [self.navigationController pushViewController:upf animated:YES];

Custom Activity Indicator, Circle Activity Indicator

UIView, UIColor, CGPoint, UIBezierPath, CABasicAnimation

ViewController.h

#import “GMDCircleLoader.h”

@property (weak, nonatomic) IBOutlet UIView *viewActivityIndicator;

ViewController.m

[GMDCircleLoader setOnView:self.viewActivityIndicator withTitle:nil animated:YES];

GMDCircleLoader.h

#import <UIKit/UIKit.h>

#import <QuartzCore/QuartzCore.h>

#import <CoreGraphics/CoreGraphics.h>

#pragma mark – Definitions

//———————————-

// To change the color and frame size of the spinner, simply change the color and frame definition here.

//———————————-

#define GMD_SPINNER_COLOR_FRONT       [UIColor colorWithRed:235.0/255.0 green:106.0/255.0 blue:63.0/255.0 alpha:1.0]

#define GMD_SPINNER_COLOR_BACK       [UIColor colorWithRed:60.0/255.0 green:271.0/255.0 blue:83.0/255.0 alpha:1.0]

#define GMD_SPINNER_FRAME       CGRectMake(40.0f, 40.0f, 40.0f, 40.0f)

#define GMD_SPINNER_IMAGE       CGRectMake(15, 15,30,30)

#define GMD_IMAGE               [UIImage imageNamed:@“image”]

#define GMD_SPINNER_LINE_WIDTH  fmaxf(self.frame.size.width * 0.055, 1.f)

#pragma mark – Interface

@interface GMDCircleLoader : UIView

@property (nonatomic, assign) CGFloat lineWidth;

@property (nonatomic, assign) UIColor *lineTintColor;

@property (nonatomic, strong) CAShapeLayer *backgroundLayer, *abackgroundLayer;

@property (nonatomic, assign) BOOL isSpinning;

– (void)start;

– (void)stop;

+ (GMDCircleLoader *)setOnView:(UIView *)view withTitle:(NSString *)title animated:(BOOL)animated;

+ (BOOL)hideFromView:(UIView *)view animated:(BOOL)animated;

@end

GMDCircleLoader.m

@implementation GMDCircleLoader

//———————————–

// Add the loader to view

//———————————–

+ (GMDCircleLoader *)setOnView:(UIView *)view withTitle:(NSString *)title animated:(BOOL)animated {

    GMDCircleLoader *hud = [[GMDCircleLoader alloc] initWithFrame:GMD_SPINNER_FRAME];

    

    //You can add an image to the center of the spinner view

    //    UIImageView *img = [[UIImageView alloc] initWithFrame:GMD_SPINNER_IMAGE];

    //    img.image = GMD_IMAGE;

    //    hud.center = img.center;

    //    [hud addSubview:img];    

    

    [hud start];

    [view addSubview:hud];

    float height = view.frame.size.height;

    float width = view.frame.size.width;

    CGPoint center = CGPointMake(width/2, height/2);

    hud.center = center;

    return hud;

}

//————————————

// Hide the leader in view

//————————————

+ (BOOL)hideFromView:(UIView *)view animated:(BOOL)animated {

    GMDCircleLoader *hud = [GMDCircleLoader HUDForView:view];

    [hud stop];

    if (hud) {

        [hud removeFromSuperview];

        return YES;

    }

    return NO;

}

//————————————

// Perform search for loader and hide it

//————————————

+ (GMDCircleLoader *)HUDForView: (UIView *)view {

    GMDCircleLoader *hud = nil;

    NSArray *subViewsArray = view.subviews;

    Class hudClass = [GMDCircleLoader class];

    for (UIView *aView in subViewsArray) {

        if ([aView isKindOfClass:hudClass]) {

            hud = (GMDCircleLoader *)aView;

        }

    }

    return hud;

}

#pragma mark – Initialization

– (instancetype)initWithFrame:(CGRect)frame {

    if ((self = [super initWithFrame:frame])) {

        [self setup];

    }

    return self;

}

#pragma mark – Setup

– (void)setup {

    self.backgroundColor = [UIColor clearColor];

    

    //—————————

    // Set line width

    //—————————

    _lineWidth = GMD_SPINNER_LINE_WIDTH;

    

    //—————————

    // Round Progress View

    //—————————

    

    self.abackgroundLayer = [CAShapeLayer layer];

    _abackgroundLayer.strokeColor = GMD_SPINNER_COLOR_BACK.CGColor;

    _abackgroundLayer.fillColor = self.backgroundColor.CGColor;

    _abackgroundLayer.lineCap = kCALineCapRound;

    _abackgroundLayer.lineWidth = _lineWidth;

    [self.layer addSublayer:_abackgroundLayer];

    

    

    

    self.backgroundLayer = [CAShapeLayer layer];

    _backgroundLayer.strokeColor = GMD_SPINNER_COLOR_FRONT.CGColor;

    _backgroundLayer.fillColor = self.backgroundColor.CGColor;

    _backgroundLayer.lineCap = kCALineCapRound;

    _backgroundLayer.lineWidth = _lineWidth;

    [self.layer addSublayer:_backgroundLayer];

    

    

    

}

– (void)drawRect:(CGRect)rect {

    //————————-

    // Make sure layers cover the whole view

    //————————-

    _backgroundLayer.frame = self.bounds;

}

#pragma mark – Drawing

– (void)drawBackgroundCircle:(BOOL) partial {

    CGFloat startAngle = – ((float)M_PI / 2); // 90 Degrees

    CGFloat endAngle = (2 * (float)M_PI) + startAngle;

    CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);

    CGFloat radius = (self.bounds.size.width_lineWidth)/2;

    

    //———————-

    // Begin draw background

    //———————-

    

    UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath];

    processBackgroundPath.lineWidth = _lineWidth;

    

    //—————————————

    // Make end angle to 90% of the progress

    //—————————————

    if (partial) {

        endAngle = (1.5f * (float)M_PI) + startAngle;

    }

    [processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];

    _backgroundLayer.path = processBackgroundPath.CGPath;

    

    

    UIBezierPath *aprocessBackgroundPath = [UIBezierPath bezierPath];

    aprocessBackgroundPath.lineWidth = _lineWidth;

    

    //—————————————

    // Make end angle to 90% of the progress

    //—————————————

    if (partial) {

        endAngle = (2.0f * (float)M_PI) + startAngle;

    }

    [aprocessBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];

    

    

    _abackgroundLayer.path = aprocessBackgroundPath.CGPath;

    

}

#pragma mark – Spin

– (void)start

{

    self.isSpinning = YES;

    [self drawBackgroundCircle:YES];

    

    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@”transform.rotation.z”];

    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];

    rotationAnimation.duration = 1;

    rotationAnimation.cumulative = YES;

    rotationAnimation.repeatCount = HUGE_VALF;

    [_backgroundLayer addAnimation:rotationAnimation forKey:@”rotationAnimation”];

    

}

– (void)stop{

    [self drawBackgroundCircle:NO];

    [_backgroundLayer removeAllAnimations];

    self.isSpinning = NO;

}

Click here to download Custom Activity Indicator, Circle Activity Indicator Project

Core Data Srudent Form

CoreData, UITextField, UIScrollView, NSNotification, NSObject

Click on Project_Name.xcdatamodeld

Creat Form entity and add below Attributes

Core Data

ViewController.h

#import “CoreDataUtility.h”

#import “Form.h”

#import “Utility.h”

<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textFieldCurrent;

@property (weak, nonatomic) IBOutlet UITextField *textFieldFirstName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldLastName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPhoneNumber;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewSignUp;

@property (weak, nonatomic) IBOutlet UITextField *textFieldRollNo;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

    

    UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];

    aGest.numberOfTapsRequired = 1;

    [self.view addGestureRecognizer:aGest];

    // Do any additional setup after loading the view, typically from a nib.

}

-(void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillShowNotification

                                                  object:nil];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillHideNotification

                                                  object:nil];

}

– (IBAction)buttonActionInsert:(id)sender

{

    NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                    self.textFieldFirstName.text,@”firstName”,

                                                    self.textFieldLastName.text,@”lastName”,

                                                    self.textFieldPhoneNumber.text,@”phoneNumber”,

                                                    self.textFieldCity.text,@”city”,

                                                    self.textFieldRollNo.text,@”rollNo”, nil];

    

    

    

    

    [CoreDataUtility insertData:dictionaryStudentDetail];

    [self resetAllTextField];

    

}

– (IBAction)buttonActionEdit:(id)sender

{

    Form *aForm = [CoreDataUtility getStudentDetailRollNo:self.textFieldRollNo.text];

    

    if (aForm != nil)

    {

        NSLog(@”%@”,aForm.firstName);

        NSLog(@”%@”,aForm.lastName);

        NSLog(@”%@”,aForm.phoneNumber);

        NSLog(@”%@”,aForm.city);

        NSLog(@”%@”,aForm.rollNo);

        

        self.textFieldFirstName.text = aForm.firstName;

        self.textFieldLastName.text = aForm.lastName;

        self.textFieldPhoneNumber.text = aForm.phoneNumber;

        self.textFieldCity.text = aForm.city;

        self.textFieldRollNo.text = aForm.rollNo;

    }

    else

    {

        NSLog(@”Record Not Found”);

        self.textFieldFirstName.text = nil;

        self.textFieldLastName.text = nil;

        self.textFieldPhoneNumber.text = nil;

        self.textFieldCity.text = nil;

        

    }

    

    

    

    

}

– (IBAction)buttonActionUpdate:(id)sender

{

    NSMutableDictionary *dictionaryStudentUpdateDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                    self.textFieldFirstName.text,@”firstName”,

                                                    self.textFieldLastName.text,@”lastName”,

                                                    self.textFieldPhoneNumber.text,@”phoneNumber”,

                                                    self.textFieldCity.text,@”city”,

                                                    self.textFieldRollNo.text,@”rollNo”, nil];

    

    

    

    

    [CoreDataUtility updateData:dictionaryStudentUpdateDetail];

    [self resetAllTextField];

    

}

– (IBAction)buttonActiondelete:(id)sender

{

    [CoreDataUtility deleteStudentDetailRollNo:self.textFieldRollNo.text];

    [self resetAllTextField];

    

}

– (IBAction)buttonActionCancel:(id)sender

{

    NSLog(@”buttonActionCancel”);

    [self resetAllTextField];

}

– (IBAction)buttonActionGetAll:(id)sender

{

    NSArray *arrayAllData = [[NSArray alloc]initWithArray:[CoreDataUtility getAllRecords]];

    NSLog(@”%@”,arrayAllData);

    

    if (arrayAllData.count > 0)

    {

        NSLog(@”%@”,[[arrayAllData objectAtIndex:0]valueForKey:@”firstName”]);

    }

    

}

– (IBAction)buttonActionDeleteAll:(id)sender

{

    [CoreDataUtility deleteAllRecords];

}

– (void)resetAllTextField

{

    self.textFieldFirstName.text = nil;

    self.textFieldLastName.text = nil;

    self.textFieldPhoneNumber.text = nil;

    self.textFieldCity.text = nil;

    self.textFieldRollNo.text = nil;

}

#pragma mark – Gester method

– (void)tapDetected {

    

    [self.textFieldCurrent resignFirstResponder];

    

}

#pragma mark – UIKeyboard show/hide notification

– (void)keyboardWillShow:(NSNotification *)iNotification {

    

    NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);

    

    NSDictionary *aKeyInfo = iNotification.userInfo;

    NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect aRect = [aRectValue CGRectValue];

    

    if (self.textFieldCurrent.tag == 4 || self.textFieldCurrent.tag == 5)

    {

        self.scrollViewSignUp.contentOffset = CGPointMake(0, (aRect.size.height) – ([UIScreen mainScreen].bounds.size.height / 6));

    }

    

}

– (void)keyboardWillHide:(NSNotification *)iNotification  {

    

    self.scrollViewSignUp.contentOffset = CGPointMake(0, 0);

    

}

#pragma mark – UITextField delegate

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    

    [textField resignFirstResponder];

    return YES;

    

}

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

    

    self.textFieldCurrent = textField;

    

}

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

CoreDataUtility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Form.h”

@interface CoreDataUtility : NSObject

+ (void)insertData:(id)aData;

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo;

+ (void)updateData:(id)aData;

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo;

+ (NSArray *)getAllRecords;

+ (void)deleteAllRecords;

@end

CoreDataUtility.m

#import “CoreDataUtility.h”

@implementation CoreDataUtility

+ (void)insertData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Form *aForm = (Form *)[NSEntityDescription insertNewObjectForEntityForName:@”Form” inManagedObjectContext:aAppDelegate.managedObjectContext];

    

    aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

    aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

    aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

    aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

    aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    

    

    NSError *error = nil;

    [aAppDelegate.managedObjectContext save:&error];

}

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo

{

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@”Form” inManagedObjectContext:aAppDelegate.managedObjectContext];

    [fetchRequest setEntity:entity];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@”rollNo == %@”, aRollNo];

    [fetchRequest setPredicate:predicate];

    

    NSError *error = nil;

    

    NSArray *fetchResults = [aAppDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    

    Form *aForm = [fetchResults lastObject];

    return aForm;

}

+ (void)updateData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    NSString *rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    Form *aForm = [self getStudentDetailRollNo:rollNo];

    

    if (aForm != nil)

    {

        aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

        aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

        aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

        aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

        aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    

        NSError *error = nil;

        [aAppDelegate.managedObjectContext save:&error];

    

    }

    else

    {

        NSLog(@”Record Not Found”);

    }

}

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo

{

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    Form *aForm = [self getStudentDetailRollNo:aRollNo];

    

    if (aForm != nil)

    {

        [aAppDelegate.managedObjectContext deleteObject:aForm];

    }

    NSError *error = nil;

    [aAppDelegate.managedObjectContext save:&error];

}

+ (NSArray *)getAllRecords

{

    AppDelegate *aAppdelegate = [UIApplication sharedApplication].delegate;

    

    NSManagedObjectContext *context =[aAppdelegate managedObjectContext];

    

    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@”Form”];

    

    NSError *error = nil;

    NSArray *arrayresults = [context executeFetchRequest:request error:&error];

    

    for (NSManagedObject *obj in arrayresults)

    {

        NSArray *keys = [[[obj entity] attributesByName] allKeys];

        NSArray *values = [[[obj entity] attributesByName] allValues];

        

        NSLog(@”%@”,keys);

        NSLog(@”%@”,values);

        

    }

    

    return arrayresults;

}

+ (void)deleteAllRecords;

{

    AppDelegate *aAppdelegate = [UIApplication sharedApplication].delegate;

    NSPersistentStore *store = [aAppdelegate.persistentStoreCoordinator.persistentStores lastObject];

    NSError *error = nil;

    NSURL *storeURL = store.URL;

    [aAppdelegate.persistentStoreCoordinator removePersistentStore:store error:&error];

    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

    

    //Make new persistent store for future saves   (Taken From Above Answer)

    if (![aAppdelegate.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

    {

        // do something with the error

        NSLog(@”%@”,error);

    }

    else

    {

        NSLog(@”Data Reset”);

    }

}

@end

Click here to download Core Data Srudent Form Project

Overlay image for App tutorial swipe left & right & close tutorial when click bottom right done text

UIImage

NSMutableArray *arrOverlayImg;

    int intOverlayImg;

arrOverlayImg = [[NSMutableArray alloc]initWithObjects:@”walkthrough-bg-01″,@”walkthrough-bg-02″,@”walkthrough-bg-03″,@”walkthrough-bg-04″, nil];

    

    [self.view bringSubviewToFront:_HomeScreenTransaparentImgvw];

    

    UITapGestureRecognizer *taprecognzr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(taprecognzractn:)];

    taprecognzr.delegate = self;

    [_HomeScreenTransaparentImgvw addGestureRecognizer:taprecognzr];

    

    

    

    UISwipeGestureRecognizer * swprecognzrright = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swpgstrrightactn:)];

    [swprecognzrright setDirection:(UISwipeGestureRecognizerDirectionRight)];

    [_HomeScreenTransaparentImgvw addGestureRecognizer:swprecognzrright];

   

    

    UISwipeGestureRecognizer * swprecognzrleeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swpgstrleftactn:)];

    [swprecognzrleeft setDirection:(UISwipeGestureRecognizerDirectionLeft)];

    [_HomeScreenTransaparentImgvw addGestureRecognizer:swprecognzrleeft];

    

-(IBAction)taprecognzractn:(UITapGestureRecognizer *)tapGstr

{

    CGFloat width = [UIScreen mainScreen].bounds.size.width;

    CGFloat height = [UIScreen mainScreen].bounds.size.height;

    NSLog(@”%f :: %f”,width,height);

    

    

    

     CGPoint tapLocation = [tapGstr locationInView:_HomeScreenTransaparentImgvw];

    

    

    NSLog(@”%f”,width-tapLocation.x);

    NSLog(@”%f”,height-tapLocation.y);

    

    if (tapLocation.x > (width – 50) && tapLocation.y > (height – 30))

    {

    //     _HomeScreenTransaparentImgvw.hidden = YES;

        NSLog(@”Hide Transper Image”);

    }

    

    

}

-(IBAction)swpgstrrightactn:(id)sender

{

    if (intOverlayImg >=1)

    {

        intOverlayImg –;

        

        _HomeScreenTransaparentImgvw.image = [UIImage imageNamed:[arrOverlayImg objectAtIndex:intOverlayImg]];

        

    }

    

}

-(IBAction)swpgstrleftactn:(id)sender

{

    if (intOverlayImg <=2)

    {

        intOverlayImg ++;

        _HomeScreenTransaparentImgvw.image = [UIImage imageNamed:[arrOverlayImg objectAtIndex:intOverlayImg]];

        

    }

}

Make call from iPhone

UIAlertController, NSString, UIDevice

if in NSObject class and class Method import #import <UIKit/UIKit.h>

– (void)makeCall:(NSString*)phoneNumber
{
UIAlertController *anAlertController=[UIAlertController alertControllerWithTitle:phoneNumber message:nil preferredStyle:UIAlertControllerStyleAlert];
//…
id rootViewController=[UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController=[((UINavigationController *)rootViewController).viewControllers objectAtIndex:0];
}

UIAlertAction *aAlertAction = [UIAlertAction actionWithTitle:@”Cancel” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

NSLog(@”Cancel”);

}];
UIAlertAction *anAlertAction = [UIAlertAction actionWithTitle:@”Call” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

NSString *aPhoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:
[[NSCharacterSet characterSetWithCharactersInString:@”+0123456789″]
invertedSet]]
componentsJoinedByString:@””];

NSLog(@”Call”);

aPhoneNumber = [@”tel://” stringByAppendingString:aPhoneNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:aPhoneNumber]];

}];

[anAlertController addAction:aAlertAction];
[anAlertController addAction:anAlertAction];

[rootViewController presentViewController:anAlertController animated:YES completion:nil];

}

Make call from iPhone

NSString, UIDevice

– (IBAction)buttonActionCallOne:(id)sender
{

NSString *PhoneNumber = self.textFieldOne.text;
NSURL *phoneUrl = [NSURL URLWithString:[NSString  stringWithFormat:@”telprompt:%@”,PhoneNumber]];

if ([[UIApplication sharedApplication] canOpenURL:phoneUrl])
{
[[UIApplication sharedApplication] openURL:phoneUrl];
}
else
{
UIAlertView *calert = [[UIAlertView alloc]initWithTitle:@”Alert” message:@”Call facility is not available!!!” delegate:nil cancelButtonTitle:@”ok” otherButtonTitles:nil, nil];
[calert show];
}

}

Get JSON File to NSArray from bundle

NSJSON, NSArray

– (NSArray *)parseStatesResponseFileName:(NSString *)aFileName FileType:(NSString *)aFileType
{
NSString *aFilePath = [[NSBundle mainBundle] pathForResource:aFileName ofType:aFileType];
NSString *aJsonContent = [NSString stringWithContentsOfFile:aFilePath encoding:NSUTF8StringEncoding error:nil];
NSData *aData = [aJsonContent dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];;;
NSError *anError;
NSArray *arrayJson = [NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&anError];
//    NSLog(@”%@”,arrayJson);
return arrayJson;
}

 

Click here to download Get JSON File to NSArray from bundle Project

Hit API get response with POST method

UICollectionView, Constant, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Hit API get response with POST method Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Hit API get response with GET method

UICollectionView, Constant, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Hit API get response with GET method Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Flicker API Integration – Download Images from Flicker and Show in CollectionView

UICollectionView, Constant, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

About Flicker Image Download Guide

https://www.flickr.com/services/api/misc.urls.html

Flicker Image Download URL formate

https://www.flickr.com/services/api/explore/flickr.photos.search

Tick mark = text – optional “USA”

Output : JSON

Do not sign call?

Click on Call Method

Go To Down side

URL: https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ad5b2954605cfc1be6f1514e5f65f6de&text=USA&format=json&nojsoncallback=1&api_sig=e47fe90b82f85261e9b047c9890eb0b4

Hit that API

URL: https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ad5b2954605cfc1be6f1514e5f65f6de&text=USA&format=json&nojsoncallback=1&api_sig=e47fe90b82f85261e9b047c9890eb0b4

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Flicker API Integration –  Download Images from Flicker and Show in CollectionView Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Download Image in Background And save in Cache and use

UICollectionView, Constant, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Download Image in Background And save in Cache and use Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Custom Delegate call method from View to ViewController OR Custom Delegate call method from ViewController to ViewController OR Custom Delegate call method from NSObject Calss to NSObject Class

UICollectionView, Constant,  DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Custom Delegate call method from View to ViewController OR Custom Delegate call method from ViewController to ViewController OR Custom Delegate call method from NSObject Calss to NSObject Class Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Creat Data Model for passing data from First ViewController to Second ViewController

UICollectionView, Constant, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Creat Data Model for passing data from First ViewController to Second ViewController Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Custom CollectionView

UICollectionView, Constant, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//    NSLog(@”%ld”,(long)indexPath.row);

//    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

   

    

    // animate the cell user tapped on

    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

    

    aFrame = cell.frame;

    aIndexPath = indexPath;

    

    NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

                         [self.collectionView bringSubviewToFront:cell];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                        // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download Custom CollectionView Project

Click here to Download AFNetworking, ImageCache, Reachability Library

Set NSString in Constant file and use that string in entire Application with NSString stringWithFormat

Constant, UIDevice, NSString

Right side bundle right click on any file

iOS – Sourse – Header File

Save as – Constant.h

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

Set device height and width in constant file and use in entire application

Constant, UIDevice

Right side bundle right click on any file

iOS – Sourse – Header File

Save as – Constant.h

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “Constant.h”

NSLog(@”%f”,WD);

    NSLog(@”%f”,HT);

typedef Data pass from View to ViewController OR Else typedef Data pass from NSObject to ViewController

UICollectionView, DataModel, typedef, Delegate, UIImage, DataPass, NSJSON

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachability;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachability = aReachable;

    self.reachability = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachability startNotifier];

    

    

    

    return YES;

}

Constant.h

#ifndef Constant_h

#define Constant_h

#define NETWORK_NOT_REACHEBLE_MESSAGE @“Please check you Internet Connection”

#define HT  [UIScreen mainScreen].bounds.size.height

#define WD  [UIScreen mainScreen].bounds.size.width

#define SERVER_URL @https://api.flickr.com/services/&#8221;

#define SERVER_IMAGE_URL @https://farm%@.staticflickr.com/%@/%@_%@.jpg&#8221;

#define SERVER_IMAGE_URL_SMALL @https://farm%@.staticflickr.com/%@/%@_%@_s.jpg&#8221;

#endif /* Constant_h */

ViewController.h

#import “CollectionViewManager.h”

#import “ImageCache.h”

#import “NetworkManager.h”

#import “ResponseDataModel.h”

#import “PhotoDataModel.h”

@property (strong, nonatomic) NSMutableArray *arrMain;

@property (nonatomic, retain) CollectionViewManager *aCollectionViewManager;

@property (strong, nonatomic) NSCache *imageCache;

@property (strong, nonatomic) ResponseDataModel *aResponseDataModelFlickerAPI;

@property (weak, nonatomic) IBOutlet UICollectionView *clctnVw;

@property (weak, nonatomic) IBOutlet UIButton *btnLoadImages;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    self.btnLoadImages.hidden = YES;

    self.arrMain = [[NSMutableArray alloc]init];

    

    self.imageCache = [[NSCache alloc]init];

    

    //Below Method id POST Method

    [[NetworkManager sharedNetworkManager] getImagesWithPOSTMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    //Below Methos is Get Method

    [[NetworkManager sharedNetworkManager] getImagesWithGETMethodFronFlickerAPIRequestParameters:nil withCompletionBlock:^(NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess) {

        

        if (isSucess)

        {

            self.btnLoadImages.hidden = NO;

            NSLog(@”%@”,responseFlickerAPI);

            

            self.aResponseDataModelFlickerAPI = responseInResponseDataModelFlickerAPI;

            NSLog(@”%@”,[Utility descriptionForObject:responseInResponseDataModelFlickerAPI]);

            

        }

        else

        {

            NSLog(@”%@”,responseFlickerAPI);

            NSLog(@”%@”,message);

        }

        

    }];

    

    

    

    NSLog(@”apple”);

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (IBAction)btnLoadImage:(id)sender

{

    

    NSLog(@”%@”,[Utility descriptionForObject:self.aResponseDataModelFlickerAPI]);

    for (PhotoDataModel *aPhotoDataModel in self.aResponseDataModelFlickerAPI.photo)

    {

        [self.arrMain addObject:aPhotoDataModel.imgaeURL];

        

    }

    

    NSLog(@”%@”,self.arrMain);

    

    self.aCollectionViewManager = [[CollectionViewManager alloc]initwithCollectionView:self.clctnVw dataSourve:self.arrMain withTapOnCollectionViewCellBlock:^(NSInteger IndexpathRow, NSString *imageURL) {

        

        NSLog(@”%ld”,(long)IndexpathRow);

        NSLog(@”%@”,imageURL);

        

        

//        NSArray* arrayStrToArray = [imageURL componentsSeparatedByString: @”/”];

//        

//        NSString *strFileName;

//        

//        NSLog(@”%@”,strFileName);

//        strFileName = [arrayStrToArray lastObject];

//        

//        UIImage *img;

//        NSData *data = [ImageCache objectForKey:strFileName];

//        if (data)

//        {

//            img = [UIImage imageWithData:data];

//        

//        }

//        else

//        {

//            img = [UIImage imageNamed:@”funny-love.jpg”];

//        }

//        

//        UIImageView *imgVw = [[UIImageView alloc]init];

//        imgVw.frame = CGRectMake(100, 100, 100, 100);

//        [self.view addSubview:imgVw];

//        NSLog(@”didSelectItemAtIndexPath”);

//        

//

//        [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

//                NSLog(@”starting animiation!”);

//                imgVw.backgroundColor = [UIColor blackColor];

//                imgVw.image = img;

//                [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

//            }completion:^(BOOL finished){

//                

//                [imgVw removeFromSuperview];

//                

//            }];

        

        

        

    }];

}

CollectionViewManager.h

#import <Foundation/Foundation.h>

#import “CollectionViewFlowLayout.h”

#import “CollectionViewCell.h”

#import “Constant.h”

typedef void (^DidTapOnCollectionViewCell)(NSInteger IndexpathRow, NSString *imageURL);

//typedef void (^DidTapOnCloseButton) (NSString *str);

@interface CollectionViewManager : NSObject<UICollectionViewDataSource,UICollectionViewDelegate,CellDelegate>

{

    CGRect aFrame;

    NSIndexPath *aIndexPath;

}

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *arrMain;

@property (nonatomic, copy) DidTapOnCollectionViewCell didTapOnCollectionViewCell;

//@property (nonatomic, copy) DidTapOnCloseButton didTapOnCloseButton;

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock;

– (void)reloadCollectionViewData;

@end

CollectionViewManager.m

#import “CollectionViewManager.h”

@implementation CollectionViewManager

-(id)initwithCollectionView:(UICollectionView *)aCollectionView dataSourve:(NSMutableArray *)aDataSource withTapOnCollectionViewCellBlock:(DidTapOnCollectionViewCell)aBlock

{

    if (self == [super init])

    {

        

    self.didTapOnCollectionViewCell = aBlock;

    self.collectionView = aCollectionView;

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    self.arrMain = aDataSource;

        

    

    }

    return self;

}

#pragma mark – CollectionView Reload

– (void)reloadCollectionViewData

{

    [self.collectionView reloadData];

}

#pragma mark – CollectionView Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.arrMain count];

}

– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *staticIdentifier = @”Cell”;

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:staticIdentifier forIndexPath:indexPath];

    [cell setupImage:[self.arrMain objectAtIndex:indexPath.row]];

    cell.delegate = self;

    cell.btnClose.tag = indexPath.row;

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    

    NSLog(@”%ld”,(long)indexPath.row);

    self.didTapOnCollectionViewCell(indexPath.row,[self.arrMain objectAtIndex:indexPath.row]);

    

    

//    // animate the cell user tapped on

//    UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

//    

//    aFrame = cell.frame;

//    aIndexPath = indexPath;

//    

//    NSLog(@”%f”,WD);

//    NSLog(@”%f”,HT);

//    

//    [UIView animateWithDuration:1.0

//                          delay:0

//                        options:(UIViewAnimationOptionAllowUserInteraction)

//                     animations:^{

//                         NSLog(@”animation start”);

//                         cell.frame = CGRectMake(WD/3, HT/3, cell.frame.size.width, cell.frame.size.height);

//                         [self.collectionView bringSubviewToFront:cell];

//                     }

//                     completion:^(BOOL finished){

//                         NSLog(@”animation end”);

//                        // [cell setBackgroundColor:[UIColor whiteColor]];

//                         

//                     }

//     ];

    

    

}

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex

{

    NSLog(@”closeButtonPressedAtCellIndex”);

    NSLog(@”%ld”,(long)cellIndex);

    [self.collectionView reloadData];

    

    UICollectionViewCell  *cell = [self.collectionView cellForItemAtIndexPath:aIndexPath];

    

//    aFrame = cell.frame;

//    aIndexPath = indexPath.row;

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         cell.frame = aFrame;

                         

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

    

}

@end

CollectionViewCell.h

#import <UIKit/UIKit.h>

#import “ImageCache.h”

#import “Utility.h”

#import “Constant.h”

@protocol CellDelegate <NSObject>

– (void)closeButtonPressedAtCellIndex:(NSInteger)cellIndex;

@end

@interface CollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) id<CellDelegate>delegate;

@property (weak, nonatomic) IBOutlet UIButton *btnClose;

@property (weak, nonatomic) IBOutlet UIImageView *imgVw;

– (void)setupImage:(NSString*)ImageUrl;

– (IBAction)btnClosePressed:(id)sender;

@end

CollectionViewCell.m

#import “CollectionViewCell.h”

@implementation CollectionViewCell

– (void)setupImage:(NSString*)ImageUrl

{

  

    NSArray* arrayStrToArray = [ImageUrl componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    NSLog(@”%@”,strFileName);

    strFileName = [arrayStrToArray lastObject];

    

    NSData *data = [ImageCache objectForKey:strFileName];

    if (data)

    {

        UIImage *image = [UIImage imageWithData:data];

        self.imgVw.image = image;

        

    }

    else

    {

        if ([Utility isNetworkReachable])

        {

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                

                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageUrl]];

                [ImageCache setObject:imgData forKey:strFileName];

                UIImage *image =   [UIImage imageWithData:imgData];

                self.imgVw.image = image;

                

            });

        }

        else

        {

            NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

            self.imgVw.image = [UIImage imageNamed:@”funny-love.jpg”];

        }        

    }

}

– (IBAction)btnClosePressed:(id)sender {

    

    NSLog(@”btnClosePressed”);

    NSLog(@”%ld”,(long)self.btnClose.tag);

    [self.delegate closeButtonPressedAtCellIndex:self.btnClose.tag];

}

@end

CollectionViewFlowLayout.h

#import <UIKit/UIKit.h>

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout

@end

CollectionViewFlowLayout.m

#import “CollectionViewFlowLayout.h”

@implementation CollectionViewFlowLayout

@end

Utility.h

#import <Foundation/Foundation.h>

#import “AppDelegate.h”

#import “Reachability.h”

@interface Utility : NSObject

+ (BOOL)isNetworkReachable;

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    

    AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    

    Reachability *netReach = [aAppDelegate reachability];

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    return isReachable;

}

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

NetworkManager.h

#import <Foundation/Foundation.h>

#import “AFHTTPSessionManager.h”

#import “AFNetworking.h”

#import “Constant.h”

#import “Reachability.h”

#import “ResponseDataModel.h”

#import “Utility.h”

@interface NetworkManager : AFHTTPSessionManager

+ (NetworkManager *)sharedNetworkManager;

– (BOOL)isInternetConnected;

// Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

//Below Method is GET Method

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock;

@end

NetworkManager.m

#import “NetworkManager.h”

@implementation NetworkManager

+ (NetworkManager *)sharedNetworkManager

{

    static NetworkManager *sharedNetworkManager = nil;

    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{

        

        sharedNetworkManager = [[self alloc]initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

        [sharedNetworkManager setupServerConnection];

        [sharedNetworkManager.reachabilityManager startMonitoring];

        

    });

    

    return sharedNetworkManager;

}

– (void)setupServerConnection

{

    self.securityPolicy.allowInvalidCertificates = YES;

    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [self setResponseSerializer:responseSerializer];

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

    [self setRequestSerializer:requestSerializer];

}

– (BOOL)isInternetConnected

{

    Reachability *reach = [Reachability reachabilityForInternetConnection];

    //(or)

   // Reachability *reach = [Reachability reachabilityWithHostName:@”http://www.google.com“];

    

    NetworkStatus netStatus = [reach currentReachabilityStatus];

    if (netStatus != NotReachable)

    {

        NSLog(@”Internet Rechable”);

        return YES;

    }

    else

    {

        NSLog(@”Network Error No Network Available “);

        return NO;

    }

    

}

//Below Method is POST Method

– (void)getImagesWithPOSTMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self POST:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:aFlickerRequest progress:^(NSProgress * _Nonnull uploadProgress) {

            

        }

           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

         {

             if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

             {

                 NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                 NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                 

                 ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                 aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                 aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                 aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                 aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                 aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                 aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                 

                 NSLog(@”%@”,aResponseDataModel);

                 NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                 

                 completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

             }

             else

             {

                 //                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                 NSString *aErrorMEssage = responseObject;

                 completionBlock (nil, nil, aErrorMEssage, NO);

             }

         }

           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

         {

             NSLog(@”%@”,error);

             NSLog(@”%@”,error.localizedDescription);

             completionBlock (nil, nil, error.localizedDescription, NO);

         }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

//Below Method is Get MEthod

– (void)getImagesWithGETMethodFronFlickerAPIRequestParameters:(NSMutableDictionary *)aFlickerRequest withCompletionBlock:(void (^) (NSMutableDictionary *responseFlickerAPI, ResponseDataModel *responseInResponseDataModelFlickerAPI, NSString *message, BOOL isSucess))completionBlock

{

    if ([self isInternetConnected])

    {

        [self GET:@”rest/?method=flickr.photos.search&api_key=9f053a84fb6b5a182d8bb57486941cbe&text=Beautyful+Girl&format=json&nojsoncallback=1&api_sig=ff4d55c09a1358e6f8aa475c98222c4f” parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

            

        }

          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)

        {

            if ([[responseObject objectForKey:@”stat”] isEqualToString:@”ok”])

            {

                NSLog(@”%@”,[responseObject objectForKey:@”photos”]);

                NSMutableDictionary *aResponseObjectInMutableDictionary = [responseObject objectForKey:@”photos”];

                

                ResponseDataModel *aResponseDataModel = [ResponseDataModel new];

                aResponseDataModel.page = [[[responseObject objectForKey:@”photos”] objectForKey:@”page”] integerValue];

                aResponseDataModel.pages = [[[responseObject objectForKey:@”photos”] objectForKey:@”pages”] integerValue];

                aResponseDataModel.perpage = [[[responseObject objectForKey:@”photos”] objectForKey:@”perpage”] integerValue];

                aResponseDataModel.photo = [[responseObject objectForKey:@”photos”] objectForKey:@”photo”];

                aResponseDataModel.photo = [aResponseDataModel asMutableArrayPhotoWithPhotoDataModel];

                aResponseDataModel.total = [[[responseObject objectForKey:@”photos”] objectForKey:@”total”] integerValue];

                

                NSLog(@”%@”,aResponseDataModel);

                NSLog(@”%@”,[Utility descriptionForObject:aResponseDataModel]);

                

                completionBlock (aResponseObjectInMutableDictionary, aResponseDataModel, nil,YES);

            }

            else

            {

//                NSString *aErrorMessage = [responseObject objectForKey:@”message”];

                NSString *aErrorMEssage = responseObject;

                completionBlock (nil, nil, aErrorMEssage, NO);

            }

        }

          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)

        {

            NSLog(@”%@”,error);

            NSLog(@”%@”,error.localizedDescription);

            completionBlock (nil, nil, error.localizedDescription, NO);

        }];

    }

    else

    {

        NSLog(@”%@”,NETWORK_NOT_REACHEBLE_MESSAGE);

    }

    

}

@end

ResponseDataModel.h

#import <Foundation/Foundation.h>

#import “PhotoDataModel.h”

@interface ResponseDataModel : NSObject

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pages;

@property (nonatomic, assign) NSInteger perpage;

@property (strong, nonatomic) NSMutableArray *photo;

@property (nonatomic, assign) NSInteger total;

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel;

@end

ResponseDataModel.m

#import “ResponseDataModel.h”

@implementation ResponseDataModel

– (NSMutableArray *)asMutableArrayPhotoWithPhotoDataModel

{

    NSMutableArray *arrayPhotoes = [NSMutableArray new];

    

    

    if (self.photo != nil)

    {

        for (NSDictionary *dic in self.photo)

        {

            PhotoDataModel *aPhotoDataModel = [PhotoDataModel new];

            aPhotoDataModel.farm = [dic objectForKey:@”farm”];

            aPhotoDataModel.aid = [dic objectForKey:@”id”];

            aPhotoDataModel.isfamily = [dic objectForKey:@”isfamily”];

            aPhotoDataModel.isfriend = [dic objectForKey:@”isfriend”];

            aPhotoDataModel.ispublic = [dic objectForKey:@”ispublic”];

            aPhotoDataModel.owner = [dic objectForKey:@”owner”];

            aPhotoDataModel.secret = [dic objectForKey:@”secret”];

            aPhotoDataModel.server = [dic objectForKey:@”server”];

            aPhotoDataModel.title = [dic objectForKey:@”title”];

            aPhotoDataModel.imgaeURL = [aPhotoDataModel getImgaeURL];

            

            [arrayPhotoes addObject:aPhotoDataModel];

            

        }

        

        NSLog(@”%@”,arrayPhotoes);

    }

    

    return arrayPhotoes;

}

@end

PhotoDataModel.h

#import <Foundation/Foundation.h>

#import “Constant.h”

@interface PhotoDataModel : NSObject

@property (strong, nonatomic) NSString *farm;

@property (strong, nonatomic) NSString *aid;

@property (strong, nonatomic) NSString *isfamily;

@property (strong, nonatomic) NSString *isfriend;

@property (strong, nonatomic) NSString *ispublic;

@property (strong, nonatomic) NSString *owner;

@property (strong, nonatomic) NSString *secret;

@property (strong, nonatomic) NSString *server;

@property (strong, nonatomic) NSString *title;

@property (strong, nonatomic) NSString *imgaeURL;

– (NSString *)getImgaeURL;

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel;

@end

PhotoDataModel.m

#import “PhotoDataModel.h”

@implementation PhotoDataModel

– (NSString *)getImgaeURL

{

    //SERVER_IMAGE_URL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg”

    //SERVER_IMAGE_URL_SMALL @”https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_s.jpg”

    

    NSString *stringImageURL;

    stringImageURL = [NSString stringWithFormat:SERVER_IMAGE_URL_SMALL,self.farm,self.server,self.aid,self.secret];

    return stringImageURL;

}

– (NSMutableDictionary *)asMutableDictionaryPhotoDataModel

{

    NSMutableDictionary *aDictionaryPhotoDataModel = [NSMutableDictionary new];

    [aDictionaryPhotoDataModel setObject:(self.farm == nil ? @””:self.farm) forKey:@”farm”];

    [aDictionaryPhotoDataModel setObject:(self.aid == nil ? @””:self.aid) forKey:@”aid”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfamily) forKey:@”isfamily”];

    [aDictionaryPhotoDataModel setObject:(self.isfamily == nil ? @””:self.isfriend) forKey:@”isfriend”];

    [aDictionaryPhotoDataModel setObject:(self.ispublic == nil ? @””:self.ispublic) forKey:@”ispublic”];

    [aDictionaryPhotoDataModel setObject:(self.owner == nil ? @””:self.owner) forKey:@”owner”];

    [aDictionaryPhotoDataModel setObject:(self.secret == nil ? @””:self.secret) forKey:@”secret”];

    [aDictionaryPhotoDataModel setObject:(self.server == nil ? @””:self.server) forKey:@”server”];

    [aDictionaryPhotoDataModel setObject:(self.title == nil ? @””:self.title) forKey:@”title”];

    

    return aDictionaryPhotoDataModel;

}

@end

Click here to Download typedef Data pass from View to ViewController OR Else typedef Data pass from NSObject to ViewController Project

Click here to Download AFNetworking, ImageCache, Reachability Library

TextField Set cornerRadius, Set borderWidth, Set borderColor Programetically

UITextField

self.txtFldReferalCode.layer.cornerRadius = 11;

    self.txtFldReferalCode.layer.borderWidth = 1;

    self.txtFldReferalCode.layer.borderColor = [[UIColor colorWithRed:58.0/255.0

                                                                green:106.0/255.0

                                                                 blue:117.0/255.0

                                                                alpha:1.0] CGColor];

Image, View or ImageView show in big frame with Animation

UIImage, UIImageView, UIView

  UIImage *img = [UIImage imageNamed:@”funny-love.jpg”];

    UIImageView *imgVw = [[UIImageView alloc]init];

    imgVw.frame = CGRectMake(100, 100, 100, 100);

    imgVw.image = img;

    [self.view addSubview:imgVw];

    

    [UIView animateWithDuration:1.0

                          delay:0

                        options:(UIViewAnimationOptionAllowUserInteraction)

                     animations:^{

                         NSLog(@”animation start”);

                         imgVw.frame = CGRectMake(100, 100, imgVw.frame.size.width, imgVw.frame.size.height);

                         [self.view bringSubviewToFront:imgVw];

                     }

                     completion:^(BOOL finished){

                         NSLog(@”animation end”);

                         // [cell setBackgroundColor:[UIColor whiteColor]];

                         

                     }

     ];

Image, View or ImageView show in big frame with Animation

UIImage, UIImageView, UIView

UIImage *img = [UIImage imageNamed:@”funny-love.jpg”];

    UIImageView *imgVw = [[UIImageView alloc]init];

    imgVw.frame = CGRectMake(100, 100, 100, 100);

    [self.view addSubview:imgVw];

    [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

        NSLog(@”starting animiation!”);

        imgVw.backgroundColor = [UIColor blackColor];

        imgVw.image = img;

        [imgVw setFrame:CGRectMake(100, 100, 200, 200)];

    }completion:^(BOOL finished){

        

    }];

When textfield start editing Keyboard will show and view go to upside after when click on view keyboard will hide view go to down side

UIScrollView, UITextField, NSNotification, UIGestureRecognizer, PassData

<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textFieldCurrent;

@property (weak, nonatomic) IBOutlet UITextField *textFieldFirstName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldLastName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPhoneNumber;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewSignUp;

– (void)viewDidLoad {

    [super viewDidLoad];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

    

    UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];

    aGest.numberOfTapsRequired = 1;

    [self.view addGestureRecognizer:aGest];

    // Do any additional setup after loading the view, typically from a nib.

}

-(void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillShowNotification

                                                  object:nil];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillHideNotification

                                                  object:nil];

}

#pragma mark – Gester method

– (void)tapDetected {

    

    [self.textFieldCurrent resignFirstResponder];

    

}

#pragma mark – UIKeyboard show/hide notification

– (void)keyboardWillShow:(NSNotification *)iNotification {

    

    NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);

    

    NSDictionary *aKeyInfo = iNotification.userInfo;

    NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect aRect = [aRectValue CGRectValue];

    

    if (self.textFieldCurrent.tag == 3 || self.textFieldCurrent.tag == 4)

    {

        self.scrollViewSignUp.contentOffset = CGPointMake(0, (aRect.size.height) – ([UIScreen mainScreen].bounds.size.height / 5.3));

    }

    

}

– (void)keyboardWillHide:(NSNotification *)iNotification  {

    

    self.scrollViewSignUp.contentOffset = CGPointMake(0, 0);

    

}

#pragma mark – UITextField delegate

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    

    [textField resignFirstResponder];

    return YES;

    

}

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

    

    self.textFieldCurrent = textField;

    

}

Click here to download When textfield start editing Keyboard will show and view go to upside after when click on view keyboard will hide view go to down side Sample Project

Pass data from ViewController to NewViewController with DataModel

PassData

ViewController.h

#import “NewViewController.h”

#import “UserDetailDataModel.h”

ViewController.m

– (IBAction)buttonActionSubmit:(id)sender

{

    NSLog(@”buttonActionSubmit”);

    

    UserDetailDataModel *aUserDetailDataModel = [UserDetailDataModel new];

    aUserDetailDataModel.FirstName = self.textFieldFirstName.text;

    aUserDetailDataModel.LastName = self.textFieldLastName.text;

    aUserDetailDataModel.PhoneNumber = self.textFieldPhoneNumber.text;

    aUserDetailDataModel.City = self.textFieldCity.text;

    

    NewViewController *aNewViewController = [self.storyboard instantiateViewControllerWithIdentifier:@”NewViewController”];

    aNewViewController.bUserDetailDataModel = aUserDetailDataModel;

    [self.navigationController pushViewController:aNewViewController animated:YES];

}

NewViewController.h

#import “UserDetailDataModel.h”

@property (strong, nonatomic) UserDetailDataModel *bUserDetailDataModel;

NewViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,self.bUserDetailDataModel);

    NSLog(@”%@”,[self.bUserDetailDataModel asMutableDictionaryUserDetailDataModel]);

    

    // Do any additional setup after loading the view.

}

UserDetailDataModel.h

#import <Foundation/Foundation.h>

@interface UserDetailDataModel : NSObject

@property (strong, nonatomic) NSString *FirstName;

@property (strong, nonatomic) NSString *LastName;

@property (strong, nonatomic) NSString *PhoneNumber;

@property (strong, nonatomic) NSString *City;

– (NSMutableDictionary *)asMutableDictionaryUserDetailDataModel;

@end

UserDetailDataModel.m

#import “UserDetailDataModel.h”

@implementation UserDetailDataModel

– (NSMutableDictionary *)asMutableDictionaryUserDetailDataModel

{

    NSMutableDictionary *aDictionaryUserDetailDataModel = [NSMutableDictionary new];

    [aDictionaryUserDetailDataModel setObject:(self.FirstName == nil ? @””:self.FirstName) forKey:@”FirstName”];

    [aDictionaryUserDetailDataModel setObject:(self.LastName == nil ? @””:self.LastName) forKey:@”LastName”];

    [aDictionaryUserDetailDataModel setObject:(self.PhoneNumber == nil ? @””:self.PhoneNumber) forKey:@”PhoneNumber”];

    [aDictionaryUserDetailDataModel setObject:(self.City == nil ? @””:self.City) forKey:@”City”];

    

    return aDictionaryUserDetailDataModel;

}

@end

Click here to download Pass data from ViewController to NewViewController with DataModel Project

All Data Model print method

NSObject, PassData

NewViewController.h

#import “UserDetailDataModel.h”

#import “Utility.h”

@property (strong, nonatomic) UserDetailDataModel *bUserDetailDataModel;

NewViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,self.bUserDetailDataModel);

    NSLog(@”%@”,[self.bUserDetailDataModel asMutableDictionaryUserDetailDataModel]);

    NSLog(@”%@”,[Utility descriptionForObject:self.bUserDetailDataModel]);

    // Do any additional setup after loading the view.

}

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

Click here to download all Data Model print method project

ScrollView Auto Layout for SignUp in 600*600 wCompact hCompact

UIScrollView, UITextField, NSNotificationCenter, UITapGestureRecognizer, PassData

In storyboard click on wCompact hCompact

Select Top Left side first four Block

Add ScrollView X = 0, Y = 0, 600*600 and add below pin

ScrollView Auto Layout for SignUp1

Add UIView X = 0, Y = 0, 600*600 and set below pin

ScrollView Auto Layout for SignUp2

Control + click Drag and drop View to ScrollView Add below constraints

ScrollView Auto Layout for SignUp3

Add view on First view X = 0, Y = 0, 600*50 and add below pin

ScrollView Auto Layout for SignUp4

Control + click Drag and drop view to first view select equal height constraints

ScrollView Auto Layout for SignUp5

go to show size inspector click on Equal Height double click on that

add multiplier 50/600

ScrollView Auto Layout for SignUp6

Add view on First view X = 0, Y = 50, 600*500 and add below pin

ScrollView Auto Layout for SignUp7

Control + click Drag and drop view to first view select equal height constraints

ScrollView Auto Layout for SignUp8

go to show size inspector click on Equal Height double click on that

add multiplier 500/600

ScrollView Auto Layout for SignUp9

Add view on First view X = 0, Y = 550, 600*50 and add below pin

ScrollView Auto Layout for SignUp10

View Differanceat with top view, middle view and bottom view for batter understanding

add label (horizontally centre and vertically centre) on top view with text Sign Up

ScrollView Auto Layout for SignUp11

Control + click Drag and drop label to view and set below constraints

ScrollView Auto Layout for SignUp12

Add one view on middle view X = centre horizontally, Y = 0, 50*50

Control + click Drag and drop inside view and select Aspect Ratio

ScrollView Auto Layout for SignUp13

Control + click Drag and drop view to Middle view add below Constraints

ScrollView Auto Layout for SignUp14

go to show size inspector click on Equal Height double click on that

add multiplier 50/500

ScrollView Auto Layout for SignUp15

Add pin on top with middle view

ScrollView Auto Layout for SignUp16

Add one UITextField X = centre horizontally, Y = 50, 400*40

Add below pin with (in middle) first view

ScrollView Auto Layout for SignUp17

ScrollView Auto Layout for SignUp18

Control + click Drag and drop textfield to Middle view add below Constraints

ScrollView Auto Layout for SignUp19

go to show size inspector click on Equal Width double click on that

add multiplier 400/600

ScrollView Auto Layout for SignUp20

go to show size inspector click on Equal Height double click on that

add multiplier 40/500

ScrollView Auto Layout for SignUp21

Add view X = centre horizontally, Y= 90, 50*50 below textfield

Add below pin with (in middle view) first textfield

ScrollView Auto Layout for SignUp22

ScrollView Auto Layout for SignUp23

Control + click Drag and drop view to (in middle view) first view add below Constraints

ScrollView Auto Layout for SignUp24

Add one UITextField X = centre horizontally, Y = 140, 400*40

Add below pin with (in middle) Second view

ScrollView Auto Layout for SignUp25

ScrollView Auto Layout for SignUp26

Control + click Drag and drop Textfield to (in middle view) first textfield add below constraints

ScrollView Auto Layout for SignUp27

Now add another view and set pin and constraints like (in middle view) Second view

then add another textfield and set pin and constraints like (in middle view) Second textfield

if you change first view height or width it will automatically effect to all view

if you change first textfield height or width it will automatically effect to all textfield

adjust all view and textfield (last view to bottom view distance should be zero ro else set whatever need)

last view set bottom constraints to middle view

ScrollView Auto Layout for SignUp28

remove constraints which is not highlight

bottom view add view X = centre horizontally, Y = Centre vertically, 200*50 inside bottom view (because want to set first button on  X = 1/4 and second button Y = (1/4)*3 if button width == 100 ) and add below Constraints

ScrollView Auto Layout for SignUp29

go to show size inspector click on Equal Width double click on that

add multiplier 200/600

ScrollView Auto Layout for SignUp30

Add submit button X = 100, Y = centre vertically in bottom view, 100*30

Add below pin to button

ScrollView Auto Layout for SignUp31

Control + click Drag and drop button to (in bottom view) view and add below constraints

ScrollView Auto Layout for SignUp32

go to show size inspector click on Equal Width double click on that

add multiplier 100/600

ScrollView Auto Layout for SignUp33

go to show size inspector click on Equal Height double click on that

add multiplier 30/50

ScrollView Auto Layout for SignUp34

Add Cancel button X = 400, Y = centre vertically in bottom view, 100*30

Add below pin to button

ScrollView Auto Layout for SignUp35

Control + click Drag and drop cancel button to submit button and add below Constraints

ScrollView Auto Layout for SignUp36

Set Place holder First Name, Last Name, Phone Number, City

Set tag for all TextField

Set delegate for all Textfield

ViewController.h

#import “NewViewController.h”

#import “UserDetailDataModel.h”

<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textFieldCurrent;

@property (weak, nonatomic) IBOutlet UITextField *textFieldFirstName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldLastName;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPhoneNumber;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewSignUp;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

    

    UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];

    aGest.numberOfTapsRequired = 1;

    [self.view addGestureRecognizer:aGest];

    // Do any additional setup after loading the view, typically from a nib.

}

-(void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillShowNotification

                                                  object:nil];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillHideNotification

                                                  object:nil];

}

– (IBAction)buttonActionSubmit:(id)sender

{

    NSLog(@”buttonActionSubmit”);

    

    UserDetailDataModel *aUserDetailDataModel = [UserDetailDataModel new];

    aUserDetailDataModel.FirstName = self.textFieldFirstName.text;

    aUserDetailDataModel.LastName = self.textFieldLastName.text;

    aUserDetailDataModel.PhoneNumber = self.textFieldPhoneNumber.text;

    aUserDetailDataModel.City = self.textFieldCity.text;

    

    NewViewController *aNewViewController = [self.storyboard instantiateViewControllerWithIdentifier:@”NewViewController”];

    aNewViewController.bUserDetailDataModel = aUserDetailDataModel;

    [self.navigationController pushViewController:aNewViewController animated:YES];

}

– (IBAction)buttonActionCancel:(id)sender

{

    NSLog(@”buttonActionCancel”);

    [self resetAllTextField];

}

– (void)resetAllTextField

{

    self.textFieldFirstName.text = nil;

    self.textFieldLastName.text = nil;

    self.textFieldPhoneNumber.text = nil;

    self.textFieldCity.text = nil;

}

#pragma mark – Gester method

– (void)tapDetected {

    

    [self.textFieldCurrent resignFirstResponder];

    

}

#pragma mark – UIKeyboard show/hide notification

– (void)keyboardWillShow:(NSNotification *)iNotification {

    

    NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);

    

    NSDictionary *aKeyInfo = iNotification.userInfo;

    NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect aRect = [aRectValue CGRectValue];

    

    if (self.textFieldCurrent.tag == 3 || self.textFieldCurrent.tag == 4)

    {

        self.scrollViewSignUp.contentOffset = CGPointMake(0, (aRect.size.height) – ([UIScreen mainScreen].bounds.size.height / 5.3));

    }

    

}

– (void)keyboardWillHide:(NSNotification *)iNotification  {

    

    self.scrollViewSignUp.contentOffset = CGPointMake(0, 0);

    

}

#pragma mark – UITextField delegate

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    

    [textField resignFirstResponder];

    return YES;

    

}

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

    

    self.textFieldCurrent = textField;

    

}

NewViewController.h

#import “UserDetailDataModel.h”

#import “Utility.h”

@property (strong, nonatomic) UserDetailDataModel *bUserDetailDataModel;

NewViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,self.bUserDetailDataModel);

    NSLog(@”%@”,[self.bUserDetailDataModel asMutableDictionaryUserDetailDataModel]);

    NSLog(@”%@”,[Utility descriptionForObject:self.bUserDetailDataModel]);

    // Do any additional setup after loading the view.

}

UserDetailDataModel.h

#import <Foundation/Foundation.h>

@interface UserDetailDataModel : NSObject

@property (strong, nonatomic) NSString *FirstName;

@property (strong, nonatomic) NSString *LastName;

@property (strong, nonatomic) NSString *PhoneNumber;

@property (strong, nonatomic) NSString *City;

– (NSMutableDictionary *)asMutableDictionaryUserDetailDataModel;

@end

UserDetailDataModel.m

#import “UserDetailDataModel.h”

@implementation UserDetailDataModel

– (NSMutableDictionary *)asMutableDictionaryUserDetailDataModel

{

    NSMutableDictionary *aDictionaryUserDetailDataModel = [NSMutableDictionary new];

    [aDictionaryUserDetailDataModel setObject:(self.FirstName == nil ? @””:self.FirstName) forKey:@”FirstName”];

    [aDictionaryUserDetailDataModel setObject:(self.LastName == nil ? @””:self.LastName) forKey:@”LastName”];

    [aDictionaryUserDetailDataModel setObject:(self.PhoneNumber == nil ? @””:self.PhoneNumber) forKey:@”PhoneNumber”];

    [aDictionaryUserDetailDataModel setObject:(self.City == nil ? @””:self.City) forKey:@”City”];

    

    return aDictionaryUserDetailDataModel;

}

@end

Utility.h

#import <Foundation/Foundation.h>

@interface Utility : NSObject

+(NSString *)descriptionForObject:(id)objct;

@end

Utility.m

#import “Utility.h”

#import <objc/message.h>

@implementation Utility

+(NSString *)descriptionForObject:(id)objct

{

    unsigned int varCount;

    NSMutableString *descriptionString = [[NSMutableString alloc]init];

    

    objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);

    

    for (int i = 0; i < varCount; i++)

    {

        objc_property_t var = vars[i];

        

        const char* name = property_getName (var);

        

        NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];

        [descriptionString appendString:keyValueString];

    }

    

    free(vars);

    return descriptionString;

}

@end

Click here to download ScrollView Auto Layout for SignUp in 600*600 wCompact hCompact Sample Project

 

 

Navigation with Segue, Data pass in Navigation with Segue

UINavigationController, UITableView

FPProductListViewController.h

#import “FPProductDetailViewController.h”

#import “FPCartViewController.h”

<UITableViewDataSource,UITableViewDelegate>

    NSArray *arysampleData;

@property (strong, nonatomic) NSMutableDictionary *dicProductDetailFrmProdctLst;

@property (strong, nonatomic) NSMutableArray *arySelectedProductsFrmPrdctLst;

@property (strong, nonatomic) NSArray *aryTableData;

@property (strong, nonatomic) IBOutlet UITableView *tblVwProductList;

FPProductListViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    

    

    arysampleData = @[ @{ @”description”: @”2016-06-14″,

                            @”Blocks”: @[ @{ @”title”: @”Block A1″,@”image”:@”0.png” },

                                          @{ @”title”: @”Block A2″,@”image”:@”1.png” },

                                          @{ @”title”: @”Block A3″,@”image”:@”3.png” },

                                          @{ @”title”: @”Block A4″,@”image”:@”4.png” },

                                          @{ @”title”: @”Block A5″,@”image”:@”5.png” },

                                          @{ @”title”: @”Block A6″,@”image”:@”6.png” },

                                          @{ @”title”: @”Block A7″,@”image”:@”7.png” },

                                          @{ @”title”: @”Block A8″,@”image”:@”8.png” },

                                          @{ @”title”: @”Block A9″,@”image”:@”9.png” },

                                          @{ @”title”: @”Block A10″,@”image”:@”10.png” }

                                          ]

                            },

                         @{ @”description”: @”2016-06-21″,

                            @”Blocks”: @[ @{ @”title”: @”Block B1″,@”image”:@”11.png” },

                                          @{ @”title”: @”Block B2″,@”image”:@”12.png” },

                                          @{ @”title”: @”Block B3″,@”image”:@”13.png” },

                                          @{ @”title”: @”Block B4″,@”image”:@”14.png” },

                                          @{ @”title”: @”Block B5″,@”image”:@”15.png” }

                                          ]

                            },

                         @{ @”description”: @”2015-09-30″,

                            @”Blocks”: @[ @{ @”title”: @”Block C1″,@”image”:@”0.png” },

                                          @{ @”title”: @”Block C2″,@”image”:@”2.png” },

                                          @{ @”title”: @”Block C3″,@”image”:@”4.png” },

                                          @{ @”title”: @”Block C4″,@”image”:@”6.png” },

                                          @{ @”title”: @”Block C5″,@”image”:@”8.png” }

                                          ]

                            },

                         ];

//    NSSortDescriptor *discriptor = [[NSSortDescriptor alloc]initWithKey:@”description” ascending:YES];

//    NSArray *descriptors = [NSArray arrayWithObject:discriptor];

//    self.aryTableData = [arysampleData sortedArrayUsingDescriptors:descriptors];

    

    

//    NSLog(@”%@”,arysampleData);

    

    

    self.aryTableData = @[ @{ @”product name”: @”Coverage Products”,

                              @”product detail”: @[@{@”ProductId”: @”1″,@”image”: @”Productimage1″,@”name”: @”SurgeShield Only”,@”detail”: @”SurgeShield is a whole-house surge protection program administered by FPL Energy Services, Inc”,@”price”:@”9.95″,@”productQuantity”: @”1″},

                                           @{@”ProductId”: @”2″,@”image”: @”Productimage2″,@”name”: @”Electronics Surge Protection Only”,@”detail”: @”surge protector. Most designs serve one immediately obvious function — they let you plug multiple components into one power outlet.”,@”price”:@”9.95″,@”productQuantity”: @”1″},

                                           @{@”ProductId”: @”3″,@”image”: @”Productimage3″,@”name”: @”Surge Protection Bundle”,@”detail”: @” Surge Protector Strip gives you the power you need for your electronic devices.”,@”price”:@”14.95″,@”productQuantity”: @”1″}]

                              },

                           ];

   NSLog(@”%@”,self.aryTableData);

    

    

    

    self.arySelectedProductsFrmPrdctLst = [[NSMutableArray alloc]init];

    

    // Do any additional setup after loading the view, typically from a nib.

}

#pragma mark – UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return [self.aryTableData count];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [[[self.aryTableData objectAtIndex:section] objectForKey:@”product detail”]count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    

    static NSString *cellIdentifier = @”Cell”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    

    

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

    

    UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:100];

    imageViewProductImage.image = [UIImage imageNamed:[[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”image”]];

    

    UILabel *labelProductName = (UILabel *)[cell viewWithTag:101];

    labelProductName.text = [[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”name”];

    

    UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

    lblProductPrice.text = [NSString stringWithFormat:@”$%@”,[[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”price”]];

    

    

    UIButton *btnAdd = (UIButton *)[cell viewWithTag:103];

    btnAdd.tag = indexPath.row;

    [btnAdd addTarget:self action:@selector(btnAddClicked:) forControlEvents:UIControlEventTouchUpInside];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

//    self.dicProductDetailFrmProdctLst = [[NSMutableDictionary alloc]init];

//    [self.dicProductDetailFrmProdctLst setObject:@”Name” forKey:@”Philippe”];

//    [self performSegueWithIdentifier:@”cellToProductDetailViewController” sender:self.dicProductDetailFrmProdctLst];

    

}

#pragma mark – UITableViewDelegate methods

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSString *header = [[self.aryTableData objectAtIndex:section]objectForKey:@”product name”];

    return header;

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

– (IBAction)btnBackClicked:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

– (IBAction)btnCartClicked:(id)sender

{

    NSLog(@”%@”,self.arySelectedProductsFrmPrdctLst);

}

– (IBAction)btnAddClicked:(UIButton*)sender

{

    NSLog(@”%ld”,sender.tag);

    

    

//    UITableViewCell *cell = (UITableViewCell *)sender.superview;

//    NSIndexPath *indexPath = [self.tblVwRef indexPathForCell:cell];

    

    UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;

    NSIndexPath *indexPath = [self.tblVwProductList indexPathForCell:cell];

    

    UIAlertController *anAlertController = [UIAlertController alertControllerWithTitle:@”” message:@”This product has been added to the cart. Do you want to view the cart?” preferredStyle:UIAlertControllerStyleAlert];

    

    UIAlertAction *anAlertActionYes = [UIAlertAction actionWithTitle:@”YES” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSLog(@”YES”);

        

        NSLog(@”%@”,self.arySelectedProductsFrmPrdctLst);

        [self performSegueWithIdentifier:@”cartBtnToCartViewController” sender:self.arySelectedProductsFrmPrdctLst];

        

        

    }];

    [anAlertController addAction:anAlertActionYes];

    

    UIAlertAction *anAlertActionNo = [UIAlertAction actionWithTitle:@”NO” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

       

        NSLog(@”NO”);

    }];

    [anAlertController addAction:anAlertActionNo];

    

    [self presentViewController:anAlertController animated:YES completion:^{

        

        NSLog(@”Completion”);

       

        [self.arySelectedProductsFrmPrdctLst addObject:[[[self.aryTableData objectAtIndex:0]objectForKey:@”product detail”]objectAtIndex:sender.tag]];

        

        

    }];

    

}

#pragma mark – Segue

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

    NSIndexPath *indexPath = [self.tblVwProductList indexPathForSelectedRow];

    NSLog(@”%ld”,indexPath.section);

    NSLog(@”%ld”,indexPath.row);

    

    if ([segue.identifier isEqualToString:@”cellToProductDetailViewController”])

    {

        FPProductDetailViewController *prdctDtlVwct = segue.destinationViewController;

        prdctDtlVwct.dicProductDetail = [[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row];

        //[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]

    }

    

    if ([segue.identifier isEqualToString:@”cartBtnToCartViewController”])

    {

        NSLog(@”cartBtnToCartViewController”);

        

        if ([self.arySelectedProductsFrmPrdctLst count] > 0)

        {

            FPCartViewController *crtVwCt = segue.destinationViewController;

            crtVwCt.arySelectedProductsFromCart = self.arySelectedProductsFrmPrdctLst;

            

        }

        else

        {

            

            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@”Please select atleast one product” preferredStyle:UIAlertControllerStyleAlert];

            

            UIAlertAction *alrtActnOk = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

               

                NSLog(@”OK”);

                

            }];

            

            [alertController addAction:alrtActnOk];

            

            [self presentViewController:alertController animated:YES completion:^{

                

            }];

            

            

        }

        

    }

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

FPCartViewController.h

<UITableViewDataSource,UITableViewDelegate>

    

    int productQuantity;

    float price;

    float totalPrice;

    BOOL isInOrderConfirmationView;

    

@property (strong, nonatomic) NSMutableArray *arySelectedProductsFromCart;

@property (weak, nonatomic) IBOutlet UITableView *tblVwSelectedProductList;

@property (weak, nonatomic) IBOutlet UIButton *btnBack;

@property (weak, nonatomic) IBOutlet UIButton *btnCheckOut;

@property (weak, nonatomic) IBOutlet UIButton *btnProceed;

@property (weak, nonatomic) IBOutlet UILabel *lblTotalPrice;

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    NSLog(@”%f”,[[[self.arySelectedProductsFromCart valueForKey:@”price”] objectAtIndex:0]floatValue]);

    totalPrice = 0;

    for (int i = 0; i<self.arySelectedProductsFromCart.count; i++)

    {

        totalPrice  = totalPrice + [[[self.arySelectedProductsFromCart valueForKey:@”price”] objectAtIndex:i]floatValue];

    }

    

    NSLog(@”%f”,totalPrice);

    

    self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

    

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    //isInOrderConfirmationView = NO;

    

    if (isInOrderConfirmationView == YES)

    {

        self.btnCheckOut.hidden = YES;

        self.btnProceed.hidden = NO;

        self.tblVwSelectedProductList.userInteractionEnabled = NO;

        

        

    }

    else

    {

        self.btnCheckOut.hidden = NO;

        self.btnProceed.hidden = YES;

        self.tblVwSelectedProductList.userInteractionEnabled = YES;

    }

    

    

}

#pragma mark – UITable View Delegates

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.arySelectedProductsFromCart count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell;

    

    

    if (isInOrderConfirmationView == NO)

    {

        static NSString *cellIdentifier = @”CellNew”;

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

            

        }

        

        

        UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:100];

        UILabel *labelProductName = (UILabel *)[cell viewWithTag:101];

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

        UIButton *btnAdd = (UIButton *)[cell viewWithTag:103];

        UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

        UIButton *btnMinus = (UIButton *)[cell viewWithTag:105];

        

        imageViewProductImage.image = [UIImage imageNamed:[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”image”]];

        

        

        labelProductName.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”name”];

        

        float tempPrice;

        tempPrice = [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”price”] floatValue] * [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”] intValue];

        

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,tempPrice];

        

        

        btnAdd.hidden = NO;

        btnAdd.tag = indexPath.row;

        [btnAdd addTarget:self action:@selector(btnAddClicked:) forControlEvents:UIControlEventTouchDown];

        

        

        lblProductQuantity.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”];

        

        btnMinus.hidden = NO;

        btnMinus.tag = indexPath.row;

        [btnMinus addTarget:self action:@selector(btnMinusClicked:) forControlEvents:UIControlEventTouchDown];

    }

    else

    {

        static NSString *cellIdentifier = @”CellForOrderSummary”;

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

            

        }

        

        UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:106];

        UILabel *labelProductName = (UILabel *)[cell viewWithTag:107];

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:108];

        

        imageViewProductImage.image = [UIImage imageNamed:[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”image”]];

        labelProductName.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”name”];

        //lblProductPrice.text = [[self.arySelectedProducts objectAtIndex:indexPath.row] objectForKey:@”detail”];

        

        float tempTotalPrice = [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”price”] floatValue] * [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”] intValue];

        

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,tempTotalPrice];

    }

    

    

    

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

   

}

#pragma mark – UITableViewDelegate methods

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSString *header = @”Selected Products”;

    return header;

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 70.0;

}

– (IBAction)btnBackClicked:(id)sender

{

  //  [self.arySelectedProductsFromCart removeAllObjects];

    

    if (isInOrderConfirmationView == NO)

    {

     [self.navigationController popViewControllerAnimated:YES];

    }

    else

    {

        isInOrderConfirmationView = NO;

        self.btnProceed.hidden = YES;

        self.btnCheckOut.hidden = NO;

        self.tblVwSelectedProductList.userInteractionEnabled = YES;

        [self.tblVwSelectedProductList reloadData];

        

    }

    

    

}

– (IBAction)btnCheckOutClicked:(id)sender {

    

    

    if ([self.arySelectedProductsFromCart count] <= 0 )

    {

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@”Please select atleast one product” preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *alrtActnOk = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

            NSLog(@”OK”);

            

        }];

        

        [alertController addAction:alrtActnOk];

        

        [self presentViewController:alertController animated:YES completion:^{

            

        }];

        

    }

    else

    {

        isInOrderConfirmationView = YES;

        self.btnProceed.hidden = NO;

        self.btnCheckOut.hidden = YES;

        self.tblVwSelectedProductList.userInteractionEnabled = NO;

        [self.tblVwSelectedProductList reloadData];

    }

    

    

    

   

    

}

– (IBAction)btnProceedClicked:(id)sender

{

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

   

    

}

– (IBAction)btnAddClicked:(UIButton *)sender

{

    NSLog(@”%ld”,sender.tag);

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    productQuantity = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”productQuantity”] intValue];

    productQuantity ++;

    

    price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

    price = price * productQuantity ;

    

     NSMutableDictionary *dicCurrentSelectedProduct = [[NSMutableDictionary alloc]init];

    dicCurrentSelectedProduct = [[self.arySelectedProductsFromCart objectAtIndex:sender.tag] mutableCopy];

    [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%d”,productQuantity] forKey:@”productQuantity”];

   // [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%f”,price] forKey:@”price”];

    [self.arySelectedProductsFromCart replaceObjectAtIndex:sender.tag withObject:dicCurrentSelectedProduct];

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    

    UITableViewCell *cell;

    NSIndexPath *indexPath;

    indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:0]; // if section is 0

    cell = (UITableViewCell*)[self.tblVwSelectedProductList cellForRowAtIndexPath:indexPath];

    

    UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

    lblProductQuantity.text = [NSString stringWithFormat:@”%d”,productQuantity];

    

    UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

    lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,price];

    

    totalPrice = totalPrice + [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

    self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

    

}

– (IBAction)btnMinusClicked:(UIButton *)sender

{

    NSLog(@”%ld”,sender.tag);

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    productQuantity = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”productQuantity”] intValue];

    

    if (productQuantity == 1)

    {

    

        UIAlertController *alrtController = [UIAlertController alertControllerWithTitle:nil message:@”Do you want to remove this product from order list?” preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *alrtActnYes = [UIAlertAction actionWithTitle:@”YES” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

            price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

            totalPrice = totalPriceprice;

            

            if (totalPrice < 0)

            {

                self.lblTotalPrice.text = @”$0.00″;

            }

            else

            {

                self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

            }

            

            

            [self.arySelectedProductsFromCart removeObjectAtIndex:sender.tag];

            [self.tblVwSelectedProductList reloadData];

            

        }];

        [alrtController addAction:alrtActnYes];

        

        UIAlertAction *alrtActnNo = [UIAlertAction actionWithTitle:@”NO” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

        }];

        [alrtController addAction:alrtActnNo];

        

        [self presentViewController:alrtController animated:YES completion:^{

            

        }];

        

        

    }

    else

    {

    productQuantity –;

        

        price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

        price = price * productQuantity ;

        

        

    NSMutableDictionary *dicCurrentSelectedProduct = [[NSMutableDictionary alloc]init];

    dicCurrentSelectedProduct = [[self.arySelectedProductsFromCart objectAtIndex:sender.tag] mutableCopy];

    [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%d”,productQuantity] forKey:@”productQuantity”];

    [self.arySelectedProductsFromCart replaceObjectAtIndex:sender.tag withObject:dicCurrentSelectedProduct];

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    NSIndexPath *indexPath;

    UITableViewCell *cell;

    indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:0]; // if section is 0

    cell = (UITableViewCell*)[self.tblVwSelectedProductList cellForRowAtIndexPath:indexPath];

    UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

    lblProductQuantity.text = [NSString stringWithFormat:@”%d”,productQuantity];

        

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,price];

        

        totalPrice = totalPrice – [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

        self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

        

    }

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

FPProductDetailViewController.h

@property (strong,nonatomic) NSMutableDictionary *dicProductDetail;

@property (weak, nonatomic) IBOutlet UIImageView *imgVwProductImage;

@property (weak, nonatomic) IBOutlet UILabel *lblProductInformation;

@property (weak, nonatomic) IBOutlet UILabel *lblProductDetail;

FPProductDetailViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    NSLog(@”%@”,self.dicProductDetail);

    

    self.imgVwProductImage.image = [UIImage imageNamed:[self.dicProductDetail objectForKey:@”image”]];

    self.lblProductInformation.text = [self.dicProductDetail objectForKey:@”name”];

    self.lblProductDetail.text = [self.dicProductDetail objectForKey:@”detail”];

    

    // Do any additional setup after loading the view.

}

– (IBAction)btnActnBack:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

Click here to download Navigation with Segue OR Data pass in Navigation with Segue Sample Project

Custom tableview with searchbar

UITableView, UISearchBar

FPOrderDetailsClass.h

@interface FPOrderDetailsClass : NSObject

@property(strong,nonatomic)NSString *orders;

@property(strong,nonatomic)NSString *firstname;

@property(strong,nonatomic)NSString *lastname;

@property(strong,nonatomic)NSString *orderdate;

@property(strong,nonatomic)NSString *city;

@property(strong,nonatomic)NSString *state;

@property(strong,nonatomic)NSString *price;

@property(strong,nonatomic)NSArray *productsList;

@end

FPOrderDetailsClass.m

@implementation FPOrderDetailsClass

@end

FPSearchCustomOrdersViewController.h

<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate>

NSArray *searchResults;

    NSArray *allArrays;

@property (strong, nonatomic) IBOutlet UITableView *myTableView;

FPSearchCustomOrdersViewController.m

#import “FPOrderDetailsClass.h”

#import “FPSearchCustomerOrderTableViewCell.h”

#import “FPSearchCustomerDetailViewController.h”

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    

    

    FPOrderDetailsClass *custom1=[FPOrderDetailsClass new];

    custom1.orders=@”1″;

    custom1.firstname=@”Daniel”;

    custom1.lastname=@”Anthony”;

    custom1.orderdate=@”1/1/2016″;

    custom1.price=@”$19.90″;

    custom1.city=@”Dallas”;

    custom1.state=@”TX”;

     NSDictionary *dic1 = [[NSDictionary alloc]initWithObjectsAndKeys:@”Productimage1.png”,@”image”,@”SurgeShield Only”,@”name”,@”$9.95 plus tax”,@”detail”,nil];

    

     NSDictionary *dic2 = [[NSDictionary alloc]initWithObjectsAndKeys:@”Productimage2.png”,@”image”,@”Electronics Surge Protection Only”,@”name”,@”$9.95 plus tax” ,@”detail”,nil];

    

    NSArray *arr = [[NSArray alloc]initWithObjects:dic1,dic2, nil];

    custom1.productsList = arr;

    

    

    NSLog(@”%@”,custom1.productsList);

    

    

    FPOrderDetailsClass *custom2=[FPOrderDetailsClass new];

    custom2.orders=@”2″;

    custom2.firstname=@”James”;

    custom2.lastname=@”William”;

    custom2.orderdate=@”3/2/2016″;

    custom2.price=@”$19.90″;

    custom2.city=@”Columbus”;

    custom2.state=@”OH”;

    custom2.productsList=arr;

    

    FPOrderDetailsClass *custom3=[FPOrderDetailsClass new];

    custom3.orders=@”3″;

    custom3.firstname=@”David”;

    custom3.lastname=@”Andrew”;

    custom3.orderdate=@”5/3/2016″;

    custom3.price=@”$19.90″;

    custom3.city=@”New york”;

    custom3.state=@”NY”;

    custom3.productsList=arr;

    

    FPOrderDetailsClass *custom4=[FPOrderDetailsClass new];

    custom4.orders=@”4″;

    custom4.firstname=@”Jacob”;

    custom4.lastname=@”kevin”;

    custom4.orderdate=@”7/4/2016″;

    custom4.price=@”$19.90″;

    custom4.city=@”Hampton”;

    custom4.state=@”VA”;

    custom4.productsList=arr;

    

    FPOrderDetailsClass *custom5=[FPOrderDetailsClass new];

    custom5.orders=@”5″;

    custom5.firstname=@”Gabriel”;

    custom5.lastname=@”John”;

    custom5.orderdate=@”7/4/2016″;

    custom5.price=@”$19.90″;

    custom5.city=@”Miami”;

    custom5.state=@”FL”;

    custom5.productsList=arr;

    

    allArrays=[NSArray arrayWithObjects:custom1,custom2,custom3,custom4,custom5,nil];

    myTableView.delegate=self;

    [myTableView reloadData];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        return [searchResults count];

        

    } else {

        return [allArrays count];

    }

    

}

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @”Cell”;

    

    

    FPSearchCustomerOrderTableViewCell *cell = (FPSearchCustomerOrderTableViewCell*)[self.myTableView dequeueReusableCellWithIdentifier:CellIdentifier];

    

    if (cell == nil)

    {

        cell = [[FPSearchCustomerOrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    

    

    FPOrderDetailsClass *customcell= [FPOrderDetailsClass new];

    

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        customcell=[searchResults objectAtIndex:indexPath.row];

    }

    else

    {

        customcell=[allArrays objectAtIndex:indexPath.row];

    }

    cell.OrdersLbl.text=customcell.orders;

    cell.FtrstName.text=customcell.firstname;

    cell.LastName.text=customcell.lastname;

    cell.DateLbl.text=customcell.orderdate;

    cell.CityLbl.text=customcell.city;

    cell.StateLbl.text=customcell.state;

    cell.PriceLbl.text=customcell.price;

    cell.selectionStyle=UITableViewCellSeparatorStyleNone;

    cell.selectionStyle=UITableViewCellSeparatorStyleNone;

    return cell;

}

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (tableView == self.searchDisplayController.searchResultsTableView) {

        //        [self performSegueWithIdentifier: @”FPSearchOrderDetailViewController” sender: self];

    }

    

}

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@”cellToDetailViewController”]) {

        FPSearchCustomerDetailViewController *destViewController = segue.destinationViewController;

        

        NSIndexPath *indexPath = nil;

        if ([self.searchDisplayController isActive]) {

            indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];

            destViewController.detaillist = [searchResults objectAtIndex:indexPath.row];

            

        } else {

            indexPath = [myTableView indexPathForSelectedRow];

            destViewController.detaillist = [allArrays objectAtIndex:indexPath.row];

        }

    }

    

}

– (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope

{

    NSPredicate *namepredicate = [NSPredicate predicateWithFormat:@”firstname contains[c] %@”, searchText];

    NSPredicate *ordernumberpredicate = [NSPredicate predicateWithFormat:@”orders contains[c] %@”, searchText];

    NSPredicate *orderdatepredicate = [NSPredicate predicateWithFormat:@”orderdate contains[c] %@”, searchText];

    NSPredicate *finalpredicate=[NSCompoundPredicate orPredicateWithSubpredicates:@[namepredicate,orderdatepredicate,ordernumberpredicate]];

    

    searchResults = [allArrays filteredArrayUsingPredicate:finalpredicate];

    

    

    

}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{

    [self filterContentForSearchText:searchString

                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]

                                      objectAtIndex:[self.searchDisplayController.searchBar

                                                     selectedScopeButtonIndex]]];

    

    return YES;

}

– (IBAction)HomeScreenBackBtn:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

FPSearchCustomerDetailOrderTableViewCell.h

@interface FPSearchCustomerDetailOrderTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UIImageView *ProductImage;

@property (strong, nonatomic) IBOutlet UILabel *ProductNameLbl;

@property (strong, nonatomic) IBOutlet UILabel *ProductCostLbl;

@end

FPSearchCustomerDetailOrderTableViewCell.m

@implementation FPSearchCustomerDetailOrderTableViewCell

– (void)awakeFromNib {

    // Initialization code

}

– (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

}

@end

FPSearchCustomerDetailViewController.h

#import “FPOrderDetailsClass.h”

<UITableViewDataSource,UITableViewDelegate>

NSMutableArray *productslistArray;

    NSMutableArray *productsImagesArray;

    NSMutableArray *productsCostArray;

@property (strong, nonatomic) IBOutlet UILabel *OrderLbl;

@property(strong,nonatomic)FPOrderDetailsClass *detaillist;

@property (strong, nonatomic) IBOutlet UIButton *SearchOrdersBackBtn;

@property (weak, nonatomic) IBOutlet UITableView *tblSearchCustomDetail;

#import “FPSearchCustomerDetailOrderTableViewCell.h”

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.OrderLbl.text=[self.detaillist valueForKey:@”orders”];

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    self.tblSearchCustomDetail.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.detaillist.productsList count];

}

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    FPSearchCustomerDetailOrderTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@”Cell”];

    if (cell==nil) {

        cell=[[FPSearchCustomerDetailOrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@”Cell”];

    }

    

    cell.ProductNameLbl.text=[[self.detaillist.productsList objectAtIndex:indexPath.row]objectForKey:@”name”];

    cell.ProductImage.image=[UIImage imageNamed:[[self.detaillist.productsList objectAtIndex:indexPath.row]objectForKey:@”image”]];

    

    cell.ProductCostLbl.text=[[self.detaillist.productsList objectAtIndex:indexPath.row]objectForKey:@”detail”];

    

    cell.selectionStyle=UITableViewCellSelectionStyleNone;

    cell.selectionStyle=UITableViewCellSeparatorStyleNone;

    

    return cell;

}

/*

#pragma mark – Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

– (IBAction)SearchOrdersBackBtn:(id)sender {

    

    [self.navigationController popViewControllerAnimated:YES];

    

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

FPSearchCustomerOrderTableViewCell.h

@interface FPSearchCustomerOrderTableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *OrdersLbl;

@property (weak, nonatomic) IBOutlet UILabel *DateLbl;

@property (weak, nonatomic) IBOutlet UILabel *FtrstName;

@property (weak, nonatomic) IBOutlet UILabel *LastName;

@property (weak, nonatomic) IBOutlet UILabel *CityLbl;

@property (weak, nonatomic) IBOutlet UILabel *StateLbl;

@property (weak, nonatomic) IBOutlet UILabel *PriceLbl;

@end

FPSearchCustomerOrderTableViewCell.m

@implementation FPSearchCustomerOrderTableViewCell

– (void)awakeFromNib {

    // Initialization code

}

– (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

}

@end

Click here to download Custom tableview with searchbar

Custom TableView, Differenceate each button action in custom tableview cell, remove Specific tableviewcell from TableView

hUITableView, UINavigationController

FPProductListViewController.h

#import “FPCartViewController.h”

<UITableViewDataSource,UITableViewDelegate>

NSArray *arysampleData;

@property (strong, nonatomic) NSMutableDictionary *dicProductDetailFrmProdctLst;

@property (strong, nonatomic) NSMutableArray *arySelectedProductsFrmPrdctLst;

@property (strong, nonatomic) NSArray *aryTableData;

@property (strong, nonatomic) IBOutlet UITableView *tblVwProductList;

FPProductListViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    

    

    arysampleData = @[ @{ @”description”: @”2016-06-14″,

                            @”Blocks”: @[ @{ @”title”: @”Block A1″,@”image”:@”0.png” },

                                          @{ @”title”: @”Block A2″,@”image”:@”1.png” },

                                          @{ @”title”: @”Block A3″,@”image”:@”3.png” },

                                          @{ @”title”: @”Block A4″,@”image”:@”4.png” },

                                          @{ @”title”: @”Block A5″,@”image”:@”5.png” },

                                          @{ @”title”: @”Block A6″,@”image”:@”6.png” },

                                          @{ @”title”: @”Block A7″,@”image”:@”7.png” },

                                          @{ @”title”: @”Block A8″,@”image”:@”8.png” },

                                          @{ @”title”: @”Block A9″,@”image”:@”9.png” },

                                          @{ @”title”: @”Block A10″,@”image”:@”10.png” }

                                          ]

                            },

                         @{ @”description”: @”2016-06-21″,

                            @”Blocks”: @[ @{ @”title”: @”Block B1″,@”image”:@”11.png” },

                                          @{ @”title”: @”Block B2″,@”image”:@”12.png” },

                                          @{ @”title”: @”Block B3″,@”image”:@”13.png” },

                                          @{ @”title”: @”Block B4″,@”image”:@”14.png” },

                                          @{ @”title”: @”Block B5″,@”image”:@”15.png” }

                                          ]

                            },

                         @{ @”description”: @”2015-09-30″,

                            @”Blocks”: @[ @{ @”title”: @”Block C1″,@”image”:@”0.png” },

                                          @{ @”title”: @”Block C2″,@”image”:@”2.png” },

                                          @{ @”title”: @”Block C3″,@”image”:@”4.png” },

                                          @{ @”title”: @”Block C4″,@”image”:@”6.png” },

                                          @{ @”title”: @”Block C5″,@”image”:@”8.png” }

                                          ]

                            },

                         ];

//    NSSortDescriptor *discriptor = [[NSSortDescriptor alloc]initWithKey:@”description” ascending:YES];

//    NSArray *descriptors = [NSArray arrayWithObject:discriptor];

//    self.aryTableData = [arysampleData sortedArrayUsingDescriptors:descriptors];

    

    

//    NSLog(@”%@”,arysampleData);

    

    

    self.aryTableData = @[ @{ @”product name”: @”Coverage Products”,

                              @”product detail”: @[@{@”ProductId”: @”1″,@”image”: @”Productimage1″,@”name”: @”SurgeShield Only”,@”detail”: @”SurgeShield is a whole-house surge protection program administered by FPL Energy Services, Inc”,@”price”:@”9.95″,@”productQuantity”: @”1″},

                                           @{@”ProductId”: @”2″,@”image”: @”Productimage2″,@”name”: @”Electronics Surge Protection Only”,@”detail”: @”surge protector. Most designs serve one immediately obvious function — they let you plug multiple components into one power outlet.”,@”price”:@”9.95″,@”productQuantity”: @”1″},

                                           @{@”ProductId”: @”3″,@”image”: @”Productimage3″,@”name”: @”Surge Protection Bundle”,@”detail”: @” Surge Protector Strip gives you the power you need for your electronic devices.”,@”price”:@”14.95″,@”productQuantity”: @”1″}]

                              },

                           ];

   NSLog(@”%@”,self.aryTableData);

    

    

    

    self.arySelectedProductsFrmPrdctLst = [[NSMutableArray alloc]init];

    

    // Do any additional setup after loading the view, typically from a nib.

}

#pragma mark – UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return [self.aryTableData count];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [[[self.aryTableData objectAtIndex:section] objectForKey:@”product detail”]count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    

    static NSString *cellIdentifier = @”Cell”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    

    

    if (cell == nil) {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

    

    UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:100];

    imageViewProductImage.image = [UIImage imageNamed:[[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”image”]];

    

    UILabel *labelProductName = (UILabel *)[cell viewWithTag:101];

    labelProductName.text = [[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”name”];

    

    UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

    lblProductPrice.text = [NSString stringWithFormat:@”$%@”,[[[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]objectForKey:@”price”]];

    

    

    UIButton *btnAdd = (UIButton *)[cell viewWithTag:103];

    btnAdd.tag = indexPath.row;

    [btnAdd addTarget:self action:@selector(btnAddClicked:) forControlEvents:UIControlEventTouchUpInside];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

//    self.dicProductDetailFrmProdctLst = [[NSMutableDictionary alloc]init];

//    [self.dicProductDetailFrmProdctLst setObject:@”Name” forKey:@”Philippe”];

//    [self performSegueWithIdentifier:@”cellToProductDetailViewController” sender:self.dicProductDetailFrmProdctLst];

    

}

#pragma mark – UITableViewDelegate methods

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSString *header = [[self.aryTableData objectAtIndex:section]objectForKey:@”product name”];

    return header;

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 80;

}

– (IBAction)btnBackClicked:(id)sender

{

    [self.navigationController popViewControllerAnimated:YES];

}

– (IBAction)btnCartClicked:(id)sender

{

    NSLog(@”%@”,self.arySelectedProductsFrmPrdctLst);

}

– (IBAction)btnAddClicked:(UIButton*)sender

{

    NSLog(@”%ld”,sender.tag);

    

    

//    UITableViewCell *cell = (UITableViewCell *)sender.superview;

//    NSIndexPath *indexPath = [self.tblVwRef indexPathForCell:cell];

    

    UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;

    NSIndexPath *indexPath = [self.tblVwProductList indexPathForCell:cell];

    

    UIAlertController *anAlertController = [UIAlertController alertControllerWithTitle:@”” message:@”This product has been added to the cart. Do you want to view the cart?” preferredStyle:UIAlertControllerStyleAlert];

    

    UIAlertAction *anAlertActionYes = [UIAlertAction actionWithTitle:@”YES” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSLog(@”YES”);

        

        NSLog(@”%@”,self.arySelectedProductsFrmPrdctLst);

        [self performSegueWithIdentifier:@”cartBtnToCartViewController” sender:self.arySelectedProductsFrmPrdctLst];

        

        

    }];

    [anAlertController addAction:anAlertActionYes];

    

    UIAlertAction *anAlertActionNo = [UIAlertAction actionWithTitle:@”NO” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

       

        NSLog(@”NO”);

    }];

    [anAlertController addAction:anAlertActionNo];

    

    [self presentViewController:anAlertController animated:YES completion:^{

        

        NSLog(@”Completion”);

       

        [self.arySelectedProductsFrmPrdctLst addObject:[[[self.aryTableData objectAtIndex:0]objectForKey:@”product detail”]objectAtIndex:sender.tag]];

        

        

    }];

    

}

#pragma mark – Segue

– (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

    NSIndexPath *indexPath = [self.tblVwProductList indexPathForSelectedRow];

    NSLog(@”%ld”,indexPath.section);

    NSLog(@”%ld”,indexPath.row);

    

    if ([segue.identifier isEqualToString:@”cellToProductDetailViewController”])

    {

        FPProductDetailViewController *prdctDtlVwct = segue.destinationViewController;

        prdctDtlVwct.dicProductDetail = [[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row];

        //[[self.aryTableData objectAtIndex:indexPath.section]objectForKey:@”product detail”]objectAtIndex:indexPath.row]

    }

    

    if ([segue.identifier isEqualToString:@”cartBtnToCartViewController”])

    {

        NSLog(@”cartBtnToCartViewController”);

        

        if ([self.arySelectedProductsFrmPrdctLst count] > 0)

        {

            FPCartViewController *crtVwCt = segue.destinationViewController;

            crtVwCt.arySelectedProductsFromCart = self.arySelectedProductsFrmPrdctLst;

            

        }

        else

        {

            

            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@”Please select atleast one product” preferredStyle:UIAlertControllerStyleAlert];

            

            UIAlertAction *alrtActnOk = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

               

                NSLog(@”OK”);

                

            }];

            

            [alertController addAction:alrtActnOk];

            

            [self presentViewController:alertController animated:YES completion:^{

                

            }];

            

            

        }

        

    }

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

FPCartViewController.h

<UITableViewDataSource,UITableViewDelegate>

int productQuantity;

    float price;

    float totalPrice;

    BOOL isInOrderConfirmationView;

@property (strong, nonatomic) NSMutableArray *arySelectedProductsFromCart;

@property (weak, nonatomic) IBOutlet UITableView *tblVwSelectedProductList;

@property (weak, nonatomic) IBOutlet UIButton *btnBack;

@property (weak, nonatomic) IBOutlet UIButton *btnCheckOut;

@property (weak, nonatomic) IBOutlet UIButton *btnProceed;

@property (weak, nonatomic) IBOutlet UILabel *lblTotalPrice;

– (void)viewDidLoad {

    [super viewDidLoad];

    

    

    float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”BackGround_For_All”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

    

    

    

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    NSLog(@”%f”,[[[self.arySelectedProductsFromCart valueForKey:@”price”] objectAtIndex:0]floatValue]);

    totalPrice = 0;

    for (int i = 0; i<self.arySelectedProductsFromCart.count; i++)

    {

        totalPrice  = totalPrice + [[[self.arySelectedProductsFromCart valueForKey:@”price”] objectAtIndex:i]floatValue];

    }

    

    NSLog(@”%f”,totalPrice);

    

    self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

    

    

    // Do any additional setup after loading the view.

}

-(void)viewWillAppear:(BOOL)animated

{

    //isInOrderConfirmationView = NO;

    

    if (isInOrderConfirmationView == YES)

    {

        self.btnCheckOut.hidden = YES;

        self.btnProceed.hidden = NO;

        self.tblVwSelectedProductList.userInteractionEnabled = NO;

        

        

    }

    else

    {

        self.btnCheckOut.hidden = NO;

        self.btnProceed.hidden = YES;

        self.tblVwSelectedProductList.userInteractionEnabled = YES;

    }

    

    

}

#pragma mark – UITable View Delegates

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.arySelectedProductsFromCart count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell;

    

    

    if (isInOrderConfirmationView == NO)

    {

        static NSString *cellIdentifier = @”CellNew”;

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

            

        }

        

        

        UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:100];

        UILabel *labelProductName = (UILabel *)[cell viewWithTag:101];

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

        UIButton *btnAdd = (UIButton *)[cell viewWithTag:103];

        UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

        UIButton *btnMinus = (UIButton *)[cell viewWithTag:105];

        

        imageViewProductImage.image = [UIImage imageNamed:[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”image”]];

        

        

        labelProductName.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”name”];

        

        float tempPrice;

        tempPrice = [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”price”] floatValue] * [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”] intValue];

        

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,tempPrice];

        

        

        btnAdd.hidden = NO;

        btnAdd.tag = indexPath.row;

        [btnAdd addTarget:self action:@selector(btnAddClicked:) forControlEvents:UIControlEventTouchDown];

        

        

        lblProductQuantity.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”];

        

        btnMinus.hidden = NO;

        btnMinus.tag = indexPath.row;

        [btnMinus addTarget:self action:@selector(btnMinusClicked:) forControlEvents:UIControlEventTouchDown];

    }

    else

    {

        static NSString *cellIdentifier = @”CellForOrderSummary”;

        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

        

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

            

        }

        

        UIImageView *imageViewProductImage = (UIImageView *)[cell viewWithTag:106];

        UILabel *labelProductName = (UILabel *)[cell viewWithTag:107];

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:108];

        

        imageViewProductImage.image = [UIImage imageNamed:[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”image”]];

        labelProductName.text = [[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”name”];

        //lblProductPrice.text = [[self.arySelectedProducts objectAtIndex:indexPath.row] objectForKey:@”detail”];

        

        float tempTotalPrice = [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”price”] floatValue] * [[[self.arySelectedProductsFromCart objectAtIndex:indexPath.row] objectForKey:@”productQuantity”] intValue];

        

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,tempTotalPrice];

    }

    

    

    

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

   

}

#pragma mark – UITableViewDelegate methods

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    NSString *header = @”Selected Products”;

    return header;

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return 30.0;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 70.0;

}

– (IBAction)btnBackClicked:(id)sender

{

  //  [self.arySelectedProductsFromCart removeAllObjects];

    

    if (isInOrderConfirmationView == NO)

    {

     [self.navigationController popViewControllerAnimated:YES];

    }

    else

    {

        isInOrderConfirmationView = NO;

        self.btnProceed.hidden = YES;

        self.btnCheckOut.hidden = NO;

        self.tblVwSelectedProductList.userInteractionEnabled = YES;

        [self.tblVwSelectedProductList reloadData];

        

    }

    

    

}

– (IBAction)btnCheckOutClicked:(id)sender {

    

    

    if ([self.arySelectedProductsFromCart count] <= 0 )

    {

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@”Please select atleast one product” preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *alrtActnOk = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

            NSLog(@”OK”);

            

        }];

        

        [alertController addAction:alrtActnOk];

        

        [self presentViewController:alertController animated:YES completion:^{

            

        }];

        

    }

    else

    {

        isInOrderConfirmationView = YES;

        self.btnProceed.hidden = NO;

        self.btnCheckOut.hidden = YES;

        self.tblVwSelectedProductList.userInteractionEnabled = NO;

        [self.tblVwSelectedProductList reloadData];

    }

    

    

    

   

    

}

– (IBAction)btnProceedClicked:(id)sender

{

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

   

    

}

– (IBAction)btnAddClicked:(UIButton *)sender

{

    NSLog(@”%ld”,sender.tag);

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    productQuantity = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”productQuantity”] intValue];

    productQuantity ++;

    

    price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

    price = price * productQuantity ;

    

     NSMutableDictionary *dicCurrentSelectedProduct = [[NSMutableDictionary alloc]init];

    dicCurrentSelectedProduct = [[self.arySelectedProductsFromCart objectAtIndex:sender.tag] mutableCopy];

    [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%d”,productQuantity] forKey:@”productQuantity”];

   // [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%f”,price] forKey:@”price”];

    [self.arySelectedProductsFromCart replaceObjectAtIndex:sender.tag withObject:dicCurrentSelectedProduct];

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    

    UITableViewCell *cell;

    NSIndexPath *indexPath;

    indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:0]; // if section is 0

    cell = (UITableViewCell*)[self.tblVwSelectedProductList cellForRowAtIndexPath:indexPath];

    

    UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

    lblProductQuantity.text = [NSString stringWithFormat:@”%d”,productQuantity];

    

    UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

    lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,price];

    

    totalPrice = totalPrice + [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

    self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

    

}

– (IBAction)btnMinusClicked:(UIButton *)sender

{

    NSLog(@”%ld”,sender.tag);

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    

    productQuantity = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”productQuantity”] intValue];

    

    if (productQuantity == 1)

    {

    

        UIAlertController *alrtController = [UIAlertController alertControllerWithTitle:nil message:@”Do you want to remove this product from order list?” preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *alrtActnYes = [UIAlertAction actionWithTitle:@”YES” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

            price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

            totalPrice = totalPriceprice;

            

            if (totalPrice < 0)

            {

                self.lblTotalPrice.text = @”$0.00″;

            }

            else

            {

                self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

            }

            

            

            [self.arySelectedProductsFromCart removeObjectAtIndex:sender.tag];

            [self.tblVwSelectedProductList reloadData];

            

        }];

        [alrtController addAction:alrtActnYes];

        

        UIAlertAction *alrtActnNo = [UIAlertAction actionWithTitle:@”NO” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            

        }];

        [alrtController addAction:alrtActnNo];

        

        [self presentViewController:alrtController animated:YES completion:^{

            

        }];

        

        

    }

    else

    {

    productQuantity –;

        

        price = [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

        price = price * productQuantity ;

        

        

    NSMutableDictionary *dicCurrentSelectedProduct = [[NSMutableDictionary alloc]init];

    dicCurrentSelectedProduct = [[self.arySelectedProductsFromCart objectAtIndex:sender.tag] mutableCopy];

    [dicCurrentSelectedProduct setObject:[NSString stringWithFormat:@”%d”,productQuantity] forKey:@”productQuantity”];

    [self.arySelectedProductsFromCart replaceObjectAtIndex:sender.tag withObject:dicCurrentSelectedProduct];

    NSLog(@”%@”,self.arySelectedProductsFromCart);

    

    NSIndexPath *indexPath;

    UITableViewCell *cell;

    indexPath=[NSIndexPath indexPathForRow:sender.tag inSection:0]; // if section is 0

    cell = (UITableViewCell*)[self.tblVwSelectedProductList cellForRowAtIndexPath:indexPath];

    UILabel *lblProductQuantity = (UILabel *)[cell viewWithTag:104];

    lblProductQuantity.text = [NSString stringWithFormat:@”%d”,productQuantity];

        

        UILabel *lblProductPrice = (UILabel *)[cell viewWithTag:102];

        lblProductPrice.text = [NSString stringWithFormat:@”$%0.2f”,price];

        

        totalPrice = totalPrice – [[[self.arySelectedProductsFromCart objectAtIndex:sender.tag]objectForKey:@”price”] floatValue];

        self.lblTotalPrice.text = [NSString stringWithFormat:@”$%0.2f”,totalPrice];

        

    }

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

Click here to Download Custom TableView OR Differenceate eack button action in custom tableview cell OR remove Specific tableviewcell from TableView Sample Project

Sign up Screen, when keyboard show textfield go to up and when hide textfield go to down

UITextField, UIScrollView, UIKeyboard

– View controller in storyboard go to Show the atribute inspector set Simulated matrics Size iPhone 4-inch

– Add UISCrollView x = 0, y = 0, Width = 320, Height = 568

ScrollView_Autolayout1

– Add pin add new Constraints Top = 0,Down = 0,Right = -20,Left = -20

add constraints

ScrollView_Autolayout2

– Go to Autolayout seggestion – Update frame – Fix misplacement

ScrollView_Autolayout3

– Add UIView(View size will be What ever you want) x = 0, y = 0, Width = as per ScrollView (Or whatever you want), Height = 768(whatever you want)

– Add pin add new constraints Top = 0,Down = -200,Right = 0,Left = 0 and Tick Height then add constraints

ScrollView_Autolayout4

– Hold Command and cluck and drag mouse aero View to ScrollView and set Equal Width

ScrollView_Autolayout5

– In Document out line open View constraints Select bottom = View.bottom and go to Right Side show the size inspector set constant 0(Zero)

ScrollView_Autolayout6

– Drag and drop two label

ScrollView_Autolayout7

Select Sign UP label

Set Constraints Centre horizontaly in container

Sign up Screen1

Add pin top, Width, Height

Sign up Screen2

Click Drag and Drop from First name Textfield to abow label

Select Center Horizontally

Sign up Screen3

Add pin top, Width

Sign up Screen4

Click drag and drop from last name textfield to first name textfield

select Centre Horizontally

Add pin top, Width

Do same thing to Set constraints for all textfield

Click drag and drop from last name Submit button to country textfield

select Centre Horizontally

Add pin top, Width, Height

Set IBOutlet for ScrollView named

Set IBOutlet for all Textfield

Set tag for all Textfield

Set delegate for all Textfield

ViewController.h

<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *currentTextField;

ViewController.m

– (void)viewDidLoad {

    [super viewDidLoad];

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    

    UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];

    aGest.numberOfTapsRequired = 1;

    [self.ScrlViewSignUpVC addGestureRecognizer:aGest];

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillShowNotification

                                                  object:nil];

    

    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                    name:UIKeyboardWillHideNotification

                                                  object:nil];

}

#pragma mark – Gester method

– (void)tapDetected {

    [self.currentTextField resignFirstResponder];

}

#pragma mark – UIKeyboard show/hide notification

– (void)keyboardWillShow:(NSNotification *)iNotification {

    

    NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);

    NSDictionary *aKeyInfo = iNotification.userInfo;

    NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];

    CGRect aRect = [aRectValue CGRectValue];

    if (self.currentTextField.tag == 5 || self.currentTextField.tag == 6 || self.currentTextField.tag == 7) {

        self.ScrlViewSignUpVC.contentOffset = CGPointMake(0, (aRect.size.height) – 50);

    }

}

– (void)keyboardWillHide:(NSNotification *)iNotification  {

    self.ScrlViewSignUpVC.contentOffset = CGPointMake(0, 0);

}

#pragma mark – UITextField delegate

– (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [textField resignFirstResponder];

    return YES;

}

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

    self.currentTextField = textField;

}

Click here to Download Sign up Screen or when keyboard show textfield go to up and when hide textfield go to down Sample Project

Check Internet Reachability with Reachability library

Reachability

Click here to Download Reachability Library

Drag and Drop Reachability in Xcode project

AppDelegate.h

#import “Reachability.h”

@property (nonatomic, retain) Reachability *reachabile;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    

    Reachability *aReachable = [[Reachability alloc]init];

    self.reachabile  = aReachable;

    self.reachabile = [Reachability reachabilityWithHostName:@”apple.com”];

    [self.reachabile startNotifier];

    

    // Override point for customization after application launch.

    return YES;

}

Add new file in Xcode

iOS – Source – Cocoa Touch Class

Click Next

Class : Utility

Subclass of : NSObject

Utility.h

#import “AppDelegate.h”

#import “Reachability.h”

+ (BOOL)isNetworkReachable;

Utility.m

+ (BOOL)isNetworkReachable

{

    BOOL isReachable = NO;

    AppDelegate *aAppdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    Reachability *netReach = [aAppdelegate reachabile];

    

    NetworkStatus netStatus = [netReach currentReachabilityStatus];

    BOOL isConnectionRequired = [netReach connectionRequired];

    

    if ((netStatus == ReachableViaWiFi) || ((netStatus == ReachableViaWWAN) && !isConnectionRequired))

    {

        isReachable = YES;

    }

    

    return isReachable;

}

ViewController.h

#import “Utility.h”

ViewController.m

if ([Utility isNetworkReachable])

    {

        NSLog(@”Network Reachable”);

    }

    else

    {

        NSLog(@”Network is not Rechable”);

    }

Click here to download Check Internet Reachability with Reachability library sample Project

Google Plus login integretion and google plus share Objective C

Google Plus, Social

Open Below link

https://console.developers.google.com/apis/library?project=_

Sing In

Project name

LoginUS

I agree that my use of any services and related APIs is subject to my compliance with the applicable Terms of Service.

Select Yes

Click on Creat

Google Plus login integration1

Left Side bar click on Credentials tab

OAuth Consent Screen

Select Email address

Enter Product name shown to users

Click on Save

Google Plus login integration2

Goto Credentials Click on Creat Credentials

Click on OAuth Client ID

Select iOS

Enter Name

Enter Bundle ID

Click on Creat

Showing Popup OAuth Client Here is your client ID

Click OK

Google Plus login integration3

Creat Xcode project

Include the following frameworks in your Xcode project:

  • AddressBook.framework
  • AssetsLibrary.framework
  • Foundation.framework
  • CoreLocation.framework
  • CoreMotion.framework
  • CoreGraphics.framework
  • CoreText.framework
  • MediaPlayer.framework
  • Security.framework
  • SystemConfiguration.framework
  • UIKit.framework

Drag and Drop

  • GooglePlus.framework
  • GoogleOpenSource.framework
  • GooglePlus.bundle

AppDelegate.m

– (BOOL)application: (UIApplication *)application

            openURL: (NSURL *)url

  sourceApplication: (NSString *)sourceApplication

         annotation: (id)annotation {

    return [GPPURLHandler handleURL:url

                  sourceApplication:sourceApplication

                         annotation:annotation];

}

ViewController.h

#import <GooglePlus/GooglePlus.h>

#import <GoogleOpenSource/GoogleOpenSource.h>

@class GPPSignInButton;

<GPPSignInDelegate>

@property (weak, nonatomic) IBOutlet GPPSignInButton *signInButton;

ViewController.m

#define CLIEND_ID @“98223363200-tteph5459h1qve2js1o3vb4jqeegcghg.apps.googleusercontent.com” //add your Google Plus ClientID here

static NSString * const kClientId = CLIEND_ID;

@synthesize signInButton;

– (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    GPPSignIn *signIn = [GPPSignIn sharedInstance];

    signIn.shouldFetchGooglePlusUser = YES;

    signIn.shouldFetchGoogleUserEmail = YES;  // Uncomment to get the user’s email

    

    // You previously set kClientId in the “Initialize the Google+ client” step

    signIn.clientID = kClientId;

    

    [GPPSignIn sharedInstance].actions = [NSArray arrayWithObjects:

                                          @”http://schemas.google.com/AddActivity&#8221;,

                                          @”http://schemas.google.com/BuyActivity&#8221;,

                                          @”http://schemas.google.com/CheckInActivity&#8221;,

                                          @”http://schemas.google.com/CommentActivity&#8221;,

                                          @”http://schemas.google.com/CreateActivity&#8221;,

                                          @”http://schemas.google.com/ListenActivity&#8221;,

                                          @”http://schemas.google.com/ReserveActivity&#8221;,

                                          @”http://schemas.google.com/ReviewActivity&#8221;,

                                          nil];

    

    // Uncomment one of these two statements for the scope you chose in the previous step

    signIn.scopes = @[ kGTLAuthScopePlusLogin ];  // “https://www.googleapis.com/auth/plus.login” scope

    //signIn.scopes = @[ @”profile” ];            // “profile” scope

    

    // Optional: declare signIn.actions, see “app activities”

    signIn.delegate = self;

    

    

    [signIn trySilentAuthentication];

}

– (void)finishedWithAuth: (GTMOAuth2Authentication *)auth

                   error: (NSError *) error

{

    NSLog(@”Received error %@ and auth object %@”,error, auth);

    if (error) {

        // Do some error handling here.

    } else {

        NSLog(@”%@ %@”,[GPPSignIn sharedInstance].userEmail, [GPPSignIn sharedInstance].userID);

        [self refreshInterfaceBasedOnSignIn];

    }

}

-(void)refreshInterfaceBasedOnSignIn

{

    if ([[GPPSignIn sharedInstance] authentication]) {

        // The user is signed in.

        self.signInButton.hidden = YES;

        // Perform other actions here, such as showing a sign-out button

    } else {

        self.signInButton.hidden = NO;

        // Perform other actions here

    }

}

// Share Code

– (IBAction) didTapShare: (id)sender {

    id<GPPNativeShareBuilder> shareBuilder = [[GPPShare sharedInstance] nativeShareDialog];

    

    // This line will fill out the title, description, and thumbnail from

    // the URL that you are sharing and includes a link to that URL.

    [shareBuilder setURLToShare:[NSURL URLWithString:@”https://www.shinnxstudios.com&#8221;]];

    [shareBuilder setPrefillText:@”This is an awesome G+ Sample to share”];

   // [shareBuilder setTitle:@”Title” description:@”Descp” thumbnailURL:[NSURL URLWithString:@”https://www.fbo.com/imageurl“]];

    

    [shareBuilder open];

}

// For Signout USe this code

– (void)signOut {

    [[GPPSignIn sharedInstance] signOut];

}

// Disconnet User

– (void)disconnect {

    [[GPPSignIn sharedInstance] disconnect];

}

– (void)didDisconnectWithError:(NSError *)error {

    if (error) {

        NSLog(@”Received error %@”, error);

    } else {

        // The user is signed out and disconnected.

        // Clean up user data as specified by the Google+ terms.

    }

}

Click here to download Google Plus login integretion and google plus share sample Project