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

Leave a comment