I'm trying to get a grasp on how to use block in Objective C. In this simple app I'm writing, I'm getting a set of images as a JSON stream. I'm trying to get the images out and objectify them and then collect them into a NSMutableArray
. Below is my code
WebImage.h
#import <Foundation/Foundation.h>
@interface WebImage : NSObject <NSCopying>
@property (strong, nonatomic) NSString *imageId;
@property (strong, nonatomic) NSString *imageName;
@property (strong, nonatomic) NSString *imagePath;
- (id)initWithId:(NSString *)imageId andName:(NSString *)imageName andPath:(NSString *)imagePath;
+ (NSArray *)retrieveAllImages;
@end
WebImage.m
#import "WebImage.h"
#import "AFNetworking.h"
#define HOST_URL @"http://toonmoodz.osmium.lk/"
@implementation WebImage
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone
{
WebImage *newImage = [WebImage new];
newImage.imageId = self.imageId;
newImage.imageName = self.imageName;
newImage.imagePath = self.imagePath;
return newImage;
}
- (id)initWithId:(NSString *)imageId andName:(NSString *)imageName andPath:(NSString *)imagePath
{
if (self = [self init]) {
self.imageId = imageId;
self.imageName = imageName;
self.imagePath = imagePath;
}
return self;
}
+ (NSArray *)retrieveAllImages
{
NSMutableArray *images = [[NSMutableArray alloc] init];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:[NSString stringWithFormat:@"%@%@", HOST_URL, @"All_Images.php"] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dict = responseObject[@"Images"];
NSArray *arr = [dict allValues];
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *image = obj;
NSLog(@"%@", image);
[images addObject:[[WebImage alloc] initWithId:[image objectForKey:@"id"]
andName:[image objectForKey:@"name"]
andPath:[image objectForKey:@"image"]]];
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error in image retrieveing: %@", error.localizedDescription);
}];
return [images copy];
}
The incoming JSON stream looks like this
{
Images = (
{
createddate = "2014-01-08 12:20:24";
id = 1;
image = "images/Rock_1.png";
isEnabled = 1;
name = "Rock_1";
},
{
createddate = "2014-01-08 15:12:26";
id = 2;
image = "images/Rock_2.png";
isEnabled = 1;
name = "Rock_2";
}
);
}
My problem is I can't retrieve the image objects from the JSON string. When I debug, the compiler doesn't even go into the GET block in the retrieveAllImages
method but jumps straight to the return statement.
Can anyone please tell me how to correct this?
I've created a project demonstrating the problem I'm facing and I've uploaded it here if you wanna take a quick look.
Thank you.