Monday, 31 August 2015

Image comparison

  UIImage *image1 = [UIImage imageNamed:@"EmptyLike"];
    UIImage *image2 = [button_image imageForState:UIControlStateNormal];
    
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);


    if ([data1 isEqualToData:data2]) {

}

Saturday, 29 August 2015

Change NSDictionary with NSMutableArray value

   NSMutableDictionary *newDict = [[NSMutableDictionary alloc]init];
    NSDictionary *oldDict = (NSDictionary *)[groupsArr objectAtIndex:selectrow];
    [newDict addEntriesFromDictionary:oldDict];
    [newDict setObject:note.object forKey:groupName];
    [groupsArr replaceObjectAtIndex:selectrow withObject:newDict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:selectrow inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];

    [self.GroupsTable reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

Use the object property of NSNotificationcenter

 NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              PhoneNoTxtField.text, @"phone",
                              EmailTxtField.text, @"email",
                              nil];        
 [[NSNotificationCenter defaultCenter] postNotificationName:@"phone_email"
                                                            object:self

                                                          userInfo:dict]; 


  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addPhoneEmail:) name:@"phone_email" object:nil];

- (void)addPhoneEmail:(NSNotification *)notification {    
    NSLog(@"email: %@",[notification.userInfo objectForKey:@"email"]);
    NSLog(@"phone: %@",[notification.userInfo objectForKey:@"phone"]);
}

(OR)

[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTable" object:self.TxtGroupName.text];


 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rightMenuaction:) name:@"reloadTable" object:nil];

-(void)rightMenuaction:(NSNotification *)note
{
      NSLog(@"reload table %@",note.object);
}

Friday, 28 August 2015

NSMutableArray convert to jsonString

   NSString *jsonString;
   NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:nsmutablearray
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString  = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        

    }


Thursday, 27 August 2015

NSMutableString add NSString

NSMutableString *address = [[NSMutableString alloc]init];
 
            if (![[jsonObjects objectForKey:@"city"] isEqualToString:@""]){
                if (address.length != 0){
                    [address appendString:@","];
                }
                [address appendString:[jsonObjects objectForKey:@"city"]];
            }

string convert to json

 NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSData *objectData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                             options:NSJSONReadingMutableContainers
                                                               error:nil];
        
        NSString *strStatus =[NSString stringWithFormat:@"%@",[json objectForKey:@"Status"]];
        NSString *strMessage = [NSString stringWithFormat:@"%@",[json objectForKey:@"Message"]];

        strReg_id = [NSString stringWithFormat:@"%@",[json objectForKey:@"Regid"]];

Wednesday, 26 August 2015

Phone number format

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSString *decimalString = [components componentsJoinedByString:@""];

    NSUInteger length = decimalString.length;
    BOOL hasLeadingOne = length > 0 && [decimalString characterAtIndex:0] == '1';

    if (length == 0 || (length > 10 && !hasLeadingOne) || (length > 11)) {
        textField.text = decimalString;
        return NO;
    }

    NSUInteger index = 0;
    NSMutableString *formattedString = [NSMutableString string];

    if (hasLeadingOne) {
        [formattedString appendString:@"1 "];
        index += 1;
    }

    if (length - index > 3) {
        NSString *areaCode = [decimalString substringWithRange:NSMakeRange(index, 3)];
        [formattedString appendFormat:@"(%@) ",areaCode];
        index += 3;
    }

    if (length - index > 3) {
        NSString *prefix = [decimalString substringWithRange:NSMakeRange(index, 3)];
        [formattedString appendFormat:@"%@-",prefix];
        index += 3;
    }

    NSString *remainder = [decimalString substringFromIndex:index];
    [formattedString appendString:remainder];

    textField.text = formattedString;

    return NO;
}

(OR)

 [self.textField addTarget:self action:@selector(formatPhoneNumber) forControlEvents:UIControlEventEditingChanged];


#pragma mark - phone number formatting

- (void)formatPhoneNumber {
    
    NSString *currentString = self.textField.text;
    NSString *strippedValue = [currentString stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, currentString.length)];

    NSString *formattedString;
    if (strippedValue.length == 0) {
        formattedString = @"";
    }
    else if (strippedValue.length < 3) {
        formattedString = [NSString stringWithFormat:@"(%@", strippedValue];
    }
    else if (strippedValue.length == 3) {
        formattedString = [NSString stringWithFormat:@"(%@) ", strippedValue];
    }
    else if (strippedValue.length < 6) {
        formattedString = [NSString stringWithFormat:@"(%@) %@", [strippedValue substringToIndex:3], [strippedValue substringFromIndex:3]];
    }
    else if (strippedValue.length == 6) {
        formattedString = [NSString stringWithFormat:@"(%@) %@-", [strippedValue substringToIndex:3], [strippedValue substringFromIndex:3]];
    }
    else if (strippedValue.length <= 10) {
        formattedString = [NSString stringWithFormat:@"(%@) %@-%@", [strippedValue substringToIndex:3], [strippedValue substringWithRange:NSMakeRange(3, 3)], [strippedValue substringFromIndex:6]];
    }
    else if (strippedValue.length >= 11) {
        formattedString = [NSString stringWithFormat:@"(%@) %@-%@ x%@", [strippedValue substringToIndex:3], [strippedValue substringWithRange:NSMakeRange(3, 3)], [strippedValue substringWithRange:NSMakeRange(6, 4)], [strippedValue substringFromIndex:10]];
    }
    
    self.textField.text = formattedString;
}

Tuesday, 25 August 2015

Image upload with parameters

- (void) pushView {
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:today];
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize = 250*1024;
    
    NSData *imageData = UIImageJPEGRepresentation(snap.image, compression);
    
    while ([imageData length] > maxFileSize && compression > maxCompression)
    {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(snap.image, compression);
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@/ChatImageMucUpload_android.php",kBaseURL];

    NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:encodedString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    //date parameter
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"sImageUploadDate\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[dateString dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //userid parameter
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"sEventId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[self.sEventid dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //eventid parameter
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"sCreatorId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[self.sUserid dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    // close form
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    [request setHTTPBody:body];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    //NSLog(@"return : %@", returnString);
    
    if([returnString isEqualToString:@"2"]){
           NSLog(@"not save");

    }else{
          NSLog(@"save");
  }


php

//  database connection
require_once('DataBaseConnection.php');


$strCreatorId = mysql_real_escape_string($_POST['sCreatorId']);
$strEventId = mysql_real_escape_string($_POST['sEventId']);
$strImageUploadDate = mysql_real_escape_string($_POST['sImageUploadDate']);
if (isset($_POST['sCreatorId'])) {
$picnew_id =mysql_result(mysql_query("Select Max(eg_image_id)+1 as MaxID from eaa_gallery"),0,"MaxID");

$uploaddir = $imgurl.'Gallery/';
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;

$extension = ".".pathinfo($uploadFile, PATHINFO_EXTENSION);

$randomNumber = "img0".$sslocatID."PD".$picnew_id;
$newName = $uploadDir . $randomNumber;

if ($_FILES['userfile']['size']> 3000000) {
exit("Your file is too large."); 
}
$imageurl = 'Gallery/EventId_'.$strEventId;
if (!file_exists($imageurl)) {
$location = mkdir($imageurl, 0777, true);
}
$imageurl1 = $imageurl.'/'.$newName.$extension;
mysql_query('SET CHARACTER SET utf8');
$strSQL = "INSERT INTO eaa_gallery (eg_event_id, eg_event_creatore_id, eg_image_url, eg_upload_date, eg_status)
VALUES ('".$strEventId."','".$strCreatorId."','".$imageurl1."','".$strImageUploadDate."', 1)";

$objQuery = mysql_query($strSQL);
$arr = null;

if(!$objQuery)
{
$arr = 0;
}
else{
if (move_uploaded_file($_FILES['userfile']['tmp_name'],$imageurl1)) {

/////
$fileSize = filesize($imageurl1);

$path_to_image = $imageurl."/".$newName. $extension; //give the name of image here after slash
                 $path_to_thumbnail = $imageurl."/thumbs/".$newName;
if (!file_exists($imageurl."/thumbs/")) {
$location1 = mkdir($imageurl."/thumbs/", 0777, true);
}

                 resize(100,$path_to_thumbnail, $path_to_image);

//createThumbs($imageurl."/",$imageurl."/thumbs/",$newName);

//$arr = $imageurl1;
$arr = $imageurl."/thumbs/".$newName.$extension."-->".$fileSize;
// moving image
}else{
$arr = 2;
// Not moving
}
}
echo json_encode($arr);
mysql_close($objConnect);
}



 function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);

$black = imagecolorallocate($im, 0, 0, 0);

    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);

// Make the background transparent
imagecolortransparent($tmp, $black);

    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp, "$targetFile.$new_image_ext");
}

Thursday, 20 August 2015

PLIST files programmatically in iPhone using NSObject

viewcontroller.m


#import "PlistFile.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//To insert the data into the plist

    PlistFile *object = [[PlistFile alloc]init];
    NSMutableArray *arrValue = [object pathData:@"register"];
    NSString *pathName = [arrValue objectAtIndex:0];
    NSMutableDictionary *dictValue = [arrValue objectAtIndex:1];
    [dictValue setObject:@"viswa@aitrg.com" forKey:@"emailId"];
    [dictValue setObject:@"ait123" forKey:@"password"];
    [dictValue writeToFile:pathName atomically:YES];
    
//To reterive the data from the plist

    NSMutableDictionary *dict = [object Data:@"register"];
    NSString *username = [dict objectForKey:@"emailId"];
    NSString *password = [dict objectForKey:@"password"];
    NSLog(@"value: %@:%@",username,password);
}

PlistFile.h

@interface PlistFile : NSObject
-(NSString *)path:(NSString *)Name;
-(NSMutableArray *)pathData:(NSString *)plistName;
-(NSMutableDictionary *)Data:(NSString *)plistName;
@end

PlistFile.m

#import "PlistFile.h"

@implementation PlistFile

-(NSString *)path:(NSString *)Name{    
    NSString *fileName = [NSString stringWithFormat:@"%@.plist",Name];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pathName = [documentsDirectory stringByAppendingPathComponent:fileName];
    return pathName;
}

//Careate and save Plist file Programmatically

-(NSMutableArray *)pathData:(NSString *)plistName
{
    NSString *path = [self path:plistName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSMutableDictionary *data;
    if ([fileManager fileExistsAtPath: path]) {
        data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    }
    else {
        // If the file doesn’t exist, create an empty dictionary
        data = [[NSMutableDictionary alloc] init];
    }

    NSMutableArray *pathArray = [[NSMutableArray alloc]init];
    [pathArray addObject:path];
    [pathArray addObject:data];
    return pathArray;
}

//Retrieve Plist file Programmatically

-(NSMutableDictionary *)Data:(NSString *)plistName
{
   NSString *path = [self path:plistName];
   NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
   return savedStock;
}

@end

Tuesday, 18 August 2015

Store constants value in an iOS app

Constants.h

#define kFilterDate @"date"
#define kFilterRadius @"radius"
#define kFilterSort @"sort"

//Global Strings
#define kDividingString @" / "

//Strings
#define kTour @"Tour"

#define kToursKey @"tours"

Project_Prefix.pch

//
// Prefix header for all source files of the project
//

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "Constants.h"

#endif

(OR)

Define global constants:

Constants.h

extern NSString* const kAppBaseURL;

Constants.m

#import "Constants.h"

NSString* const kAppBaseURL = @"http://url.com/";



Project_Prefix.pch

//
// Prefix header for all source files of the project
//

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "Constants.h"

#endif

Wednesday, 12 August 2015

IOS - How to disable push notification at logout?


On logout:

[[UIApplication sharedApplication] unregisterForRemoteNotifications];

On login:

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

Tuesday, 11 August 2015

UITextView should detect links, but otherwise, should propagate touch to view below

.h

@interface LinkOnlyTextView : UITextView
@end

.m

@implementation LinkOnlyTextView

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:point inTextContainer:self.textContainer fractionOfDistanceThroughGlyph:nullptr];
    NSUInteger characterIndex = [self.layoutManager characterIndexForGlyphAtIndex:glyphIndex];
    if ([self.textStorage attribute:NSLinkAttributeName atIndex:characterIndex effectiveRange:nullptr]) {
        return self;
    }
    return nil;
}

@end

Wednesday, 5 August 2015

NSURLConnection using NSObject


ServiceConnector.h

#import <Foundation/Foundation.h>

@protocol ServiceConnectorDelegate <NSObject>

-(void)requestReturnedData:(NSMutableData*)data;
-(void)requestReturnedError:(NSString*)error;

@end

@interface ServiceConnector : NSObject <NSURLConnectionDelegate,NSURLConnectionDataDelegate>

@property (strong,nonatomic) id <ServiceConnectorDelegate> delegate;

- (void)sendRequest:(NSString*)urlStr postValue:(NSString*)postStr;

@end

ServiceConnector.m

#import "ServiceConnector.h"

@implementation ServiceConnector{
    NSMutableData *receivedData;
}

- (void)sendRequest:(NSString*)urlStr postValue:(NSString*)postStr
{
    NSMutableString *post = [NSMutableString stringWithFormat:@"%@",postStr];
    
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kBaseURL,urlStr]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if (connection) {
        receivedData = nil;
    }
}
#pragma mark - Data connection delegate -
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receivedData = [[NSMutableData alloc]init];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.delegate requestReturnedError:@"noInternet"];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    [self.delegate requestReturnedData:receivedData];//send the data to the delegate
}

@end

example:

#import "ServiceConnector.h"
@interface HomeViewController : UIViewController<ServiceConnectorDelegate>

- (void)viewDidLoad
{

    [super viewDidLoad];

ServiceConnector *serviceConnector = [[ServiceConnector alloc] init];
        serviceConnector.delegate = self;
        NSString *postValue = [NSString stringWithFormat:@"sUser_id=%@&simage_id=%@",[self.sUser_id description],deleteId];
        [serviceConnector sendRequest:@"url.php" postValue:postValue];
}

-(void)requestReturnedError:(NSString *)error{
      NSLog(@"No internet connection");
}

-(void)requestReturnedData:(NSMutableData *)data{ 
//activated when data is returned    
    id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}

Cache URL images iphone UITableview

ImageCache.h

#import <Foundation/Foundation.h>

@interface ImageCache : NSObject

@property (nonatomic, retain) NSCache *imgCache;

#pragma mark - Methods

+ (ImageCache*)sharedImageCache;

- (void) AddImage:(NSString *)imageURL img:(UIImage *)image;
- (UIImage*) GetImage:(NSString *)imageURL;
- (BOOL) DoesExist:(NSString *)imageURL;


@end

ImageCache.m

#import "ImageCache.h"

@implementation ImageCache

@synthesize imgCache;

#pragma mark - Methods

static ImageCache* sharedImageCache = nil;

+(ImageCache*)sharedImageCache
{
    @synchronized([ImageCache class])
    {
        if (!sharedImageCache)
            sharedImageCache= [[self alloc] init];

        return sharedImageCache;
    }

    return nil;
}

+(id)alloc
{
    @synchronized([ImageCache class])
    {
        NSAssert(sharedImageCache == nil, @"Attempted to allocate a second instance of a singleton.");
        sharedImageCache = [super alloc];

        return sharedImageCache;
    }

    return nil;
}

-(id)init 
{
    self = [super init];
    if (self != nil) 
    {
        imgCache = [[NSCache alloc] init];
    }

    return self;
}


- (void) AddImage:(NSString *)imageURL img:(UIImage *)image
{
    [imgCache setObject:image forKey:imageURL];
}

- (NSString*) GetImage:(NSString *)imageURL
{
    return [imgCache objectForKey:imageURL];
}

- (BOOL) DoesExist:(NSString *)imageURL
{
    if ([imgCache objectForKey:imageURL] == nil)
    {
        return false;
    }

    return true;
}


@end

Example

UIImage *image;

    // 1. Check the image cache to see if the image already exists. If so, then use it. If not, then download it.

    if ([[ImageCache sharedImageCache] DoesExist:imgUrl] == true)
    {
        image = [[ImageCache sharedImageCache] GetImage:imgUrl];
    }
    else
    {

        NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: imgUrl]];
        image = [[UIImage alloc] initWithData:imageData];

        // Add the image to the cache 
        [[ImageCache sharedImageCache] AddImage:imgUrl img:image];

(OR)


[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: imgUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                UIImage *image = [UIImage imageWithData:data];
                [[ImageCache sharedImageCache] AddImage:imgUrl img:image];


            }];

    }