Get UIImageView using Afnetworking and put it in an array - objective-c

As the title says, i need to get the image and put it in an array.
UIImageView *myImage = [[UIImageView alloc] init];
[myImage setImageWithURL:[NSURL URLWithString:#"http://host.com/images/1/1.png"] placeholderImage:[UIImage imageNamed:#"page3.png"]];
[items addObject:myImage];
the problem is that while the image is being loaded, the code continues and nothing gets put in the array, actually I guess an empty UIImageView gets inserted.
How do I go about fixing this?
On a side note I am using iCarousel to display images, in the data source it gets the images array and shows them. Can i modify iCarousel somehow?
Thanks in advance.

You can use the setImageWithURLRequest method to give a success message or execute the UI update when it has finished for example using the following method:
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
Here is an example (not tested)
[image setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"host.com/images/1/1.png"]] placeholderImage:[UIImage imageNamed:#"page3.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
//reload data here
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
//handle errors here
}

Related

setting image using AFNetworking

For some reason i can't set an image using AFNetworking. It actually proceed block case failure. I don't know why is that happening, because image URL is perfectly correct (as i suppose).
Please, take a look at following:
NSString *string = [NSString stringWithFormat:#"http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg"];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[cell.myCellImageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[cell.myCellImageView setImage:image];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];
// If it's other than 200, then show it on the console.
if (HTTPStatusCode != 200) {
NSLog(#"HTTP status code = %id", HTTPStatusCode);
}
}];
It print go image on imageView and that is what NSLog typyng:
HTTP status code = 0
Why i can't achieve such simple task?
Use this class that's already in afnetworking:
https://github.com/AFNetworking/AFNetworking/blob/master/UIKit%2BAFNetworking/UIImageView%2BAFNetworking.h
And it'd just be:
[cell.myCellImageView setImageWithURL:url];
If you want to do something more complex with the image, you could use this method instead:
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;

Make an AFNetworking operation complete before next code line after [operation start] and how to handle nested operations

I have a problem with completion block in AFNetworking, my app needs to get json data about car and use id from this json file to request another api to retrieve images before displaying all cars in uitableview. But the uitableview reload is always called before retrieving information so it displays empty table.
I have a Model.m
typedef void (^CompletionBlock)(NSArray *results);
-(void)getPhotosWithCompletionBlock: (CompletionBlock)completionBlock failureBlock: (FailureBlock)failureBlock{
NSURLRequest *request = [NSURLRequest alloc] initWithURL:[NSURL alloc] initWithString:
[NSString stringWithFormat:#"api.getPhoto"]]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
completionBlock(JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
failureBlock(JSON);
}];
[operation start];
}
ModelViewController.m
- (void)getAllModels{
NSURLRequest *request = ...;
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
for(NSDictionary *model in JSON){
Model *model = [Model alloc] initWithId:...;
[model getPhotosWithCompletionBlock: ^(NSArray *results){
model.photos = results;
}failureBlock:^(NSError *error) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
}
[_tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
But [_tableView reload] is always called before completionBlock of getPhotos method finish so there's an empty tableView, so how to make completion block finish before calling reload tableView method? I can put reload method inside completion block but it forces tableView reload many times makes app very unresponsive, I have 1 more method to retrieve model info so I cannot put reload method inside every completion blocks.
P/S: any idea for my situation without using nested afnetworking operations?
This is not an AFNetworking related question, rather a general Objective-C or
asynchronous question.
You may try to reload the table view whenever the images of one model have been loaded:
- (void)getAllModels{
NSURLRequest *request = ...;
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
for(NSDictionary *model in JSON){
Model *model = [Model alloc] initWithId:...;
[model getPhotosWithCompletionBlock: ^(NSArray *results){
dispatch_async(dispatch_get_main_queue(), ^{
model.photos = results;
[self.tableView reloadData];
});
}failureBlock:^(NSError *error) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
You likely need to fix some edge cases when an error occurs.
If there are performance issues, you need to check where they occur. One usual suspect is the creation of UIImages on the main thread. You may schedule them to another embedded async task whose completion block then forces an update of the table view, or perform this in your getPhotosWithCompletionBock method.
You may also consider to be more explicit about which cell you need to update instead just simply sending reloadData: which will also reload images which are already up to date.

Lazy Loading User Image UITableView - Updating the Image in Request Block not Working

So I am trying to lazyload a user pictures for a custom UITableView (BubbleTableView)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(#"Success");
UIBubbleTableViewCell *cell = (UIBubbleTableViewCell *)[self.bubbleTableView cellForRowAtIndexPath:indexPath];
NSBubbleData *data = [[NSBubbleData alloc] init];
data = [cell data];
data.avatar = [UIImage imageNamed:#"send.png"];
[self.profileImages setObject:image forKey:[self.commUsers objectAtIndex:x]];
//Success
[cell setData:data];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
//Failed
NSLog(#"ERROR: %#", response);
}];
[operation start];
I am trying to change the Avatar to another image and I am not using the image pulled from the net rather just an image I have stored locally (for purposes of narrowing image update problem).
So if I put the
UIBubbleTableViewCell *cell = (UIBubbleTableViewCell *)[self.bubbleTableView cellForRowAtIndexPath:indexPath];
NSBubbleData *data = [[NSBubbleData alloc] init];
data = [cell data];
data.avatar = [UIImage imageNamed:#"send.png"];
[self.profileImages setObject:image forKey:[self.commUsers objectAtIndex:x]];
//Success
[cell setData:data];
Inside the AFImageRequestOperation Block, the image doesn't update. However, if I put the exact same code outside the Block, it updates the image. I feel like I am missing something on how Blocks work. How do I fix this?
Thanks!
Try to run the UI code in the block on the main thread:
if ([NSThread isMainThread]) {
// We're currently executing on the main thread.
// We can execute the block directly.
createBubbleTableViewCell();
} else {
//non-blocking call to main thread
dispatch_sync(dispatch_get_main_queue(), createBubbleTableViewCell);
}
The checking if you are on the main thread is just for case - preventing deadlock. Also you can use dispatch_async for blocking call.
The UI code should be run always on the main thread.

Edit image before cache with AFNetworking

I am loading a bunch of images using AFNetworking and I would like to scale and apply rounded corners to these images before AFNetworking caches them.
I started out scaling and applying rounded corners to the images each time they were loaded but the completion block will also be called when the image is loaded from the cache and therefore this uses too many resources when a user scrolls a collection view filled with images.
[self.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:10.0f]
placeholderImage:kVideoCollectionViewCellVideoImagePlaceholder
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
/**
* The image is edited here and this block is called
* when the image is loaded from web and from the cache.
*/
[self.imageView setImage:image];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
DDLogError(#"%#", error);
}];
AFNetworking seems to provide a great cache for my use, especially when I enable disk caching therefore I would like to use it but I can't figure out if there's a way to edit the image before it is cached.
Does anyone know if this is possible and if so, how it can be done?
After posting the question it hit me that I may have too look in another direction that using the UIImageView+AFNetworking category. Using the AFImageRequestOperation directly solved the problem.
__weak NZVideoCollectionViewCell *weakSelf = self;
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:10.0f];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:^UIImage*(UIImage *image) {
/**
* Edit image.
*/
return editedImage;
}
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[weakSelf.imageView setImage:image];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
DDLogError(#"%#", error);
}];
[operation start];

AFImageRequestOperation wait until finished

i have a little problem with this, I'm loading an Image from a Url like this:
+ (void)getImageFromURL:(NSString *)imageFilename urlMode:(NSString *)mode block:(id (^)(UIImage *responseImage))aImage {
NSURL *url = [NSURL URLWithString:[mainURL stringByAppendingString:mode]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
AFImageRequestOperation *requestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
cacheName:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
aImage(image);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
{
// manage errors
}];
[[[NSOperationQueue alloc]init] addOperation:requestOperation];
}
I'm trying to set an iVar UIImage *userAvatar to the response from this request, but the problem is, since its an async request I'm not getting the iVar set before my Code moves on, so my iVar is empty when I'm accessing it and passing it to another method.
That's the nature of asynchronous programming! You are going to have to redesign the dependencies on userAvatar to take into account that it's availability is nondeterministic.
So, rather than having your operation's success block simply set the userAvatar ivar, it takes care of whatever needs to happen once that image is available. For example if you want to set a UIImageView's image, then in your success block:
dispatch_async(dispatch_get_main_queue(), ^{
myImageView.image = image;
});
(Without knowing the details of your goals and details of your implementation, this is just a "for example...")
You forgot to add [requestOperation start]; at the end.