//
// KFBFlickrPhotoManager.m
// KFBNewsroom
#import "KFBFlickrPhotoManager.h"
#import "KFBFlickrPhoto.h"
@implementation KFBFlickrPhotoManager
@synthesize theURL,delegate;
- (void)process {
dispatch_async(backgroundQueue, ^(void) {
[self requestFlickr];
});
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self processResults];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"error: %@",error);
}
-(void)requestFlickr
{
//NSURLConnection must be called on main thread
NSURLRequest *request = [NSURLRequest requestWithURL:theURL];
dispatch_async(dispatch_get_main_queue(), ^(void) {
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
});
}
-(void)processResults
{
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(@"error: %@",error);
}
NSArray *photos = [[results objectForKey:@"photos"] objectForKey:@"photo"];
NSMutableArray * images = [NSMutableArray array];
for (NSDictionary *photo in photos)
{
// image title
NSString *title = [photo objectForKey:@"title"];
[photoTitles addObject:(title.length > 0 ? title : @"Untitled")];
// builds URL for image, adds _s for small image (75x75)
NSString *photoURLString =
[NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_s.jpg",
[photo objectForKey:@"farm"], [photo objectForKey:@"server"],
[photo objectForKey:@"id"], [photo objectForKey:@"secret"]];
NSLog(@"photoURLString: %@", photoURLString);
KFBFlickrPhoto *flickrPhoto = [[KFBFlickrPhoto alloc] initWithSourceURL:[NSURL URLWithString:photoURLString]];
flickrPhoto.name = title;
// build an array of the image data
[images addObject:flickrPhoto];
// Build the URL to the large image
photoURLString =
[NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_b.jpg",
[photo objectForKey:@"farm"], [photo objectForKey:@"server"],
[photo objectForKey:@"id"], [photo objectForKey:@"secret"]];
[photoURLsLargeImage addObject:[NSURL URLWithString:photoURLString]];
flickrPhoto.bigImageName = [NSURL URLWithString:photoURLString];
NSLog(@"photoURLsLargeImage: %@\n\n", photoURLString);
}
// Notify delegate in main thread
dispatch_async(dispatch_get_main_queue(), ^(void) {
[delegate imagesAvailable:images done:YES];
});
}
- (id)initWithURL:(NSURL*)url delegate:(id<FlickrPhotoDelegate>) theDelegate {
if ((self = [super init])) {
theURL = url;
delegate = theDelegate;
backgroundQueue = dispatch_queue_create("com.KFB.bgqueue", NULL);
photoTitles = [NSMutableArray array];
// Image data (thumbnail)
responseData = [NSMutableData data];
photoSmallImageData = [NSMutableArray array];
photoURLsLargeImage = [NSMutableArray array];
}
return self;
}
@end