Edit image before cache with AFNetworking - objective-c

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];

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.

Reload UITableView data and not the visible cells

I'm working on an app where I want to pull data from a remote web service and populate a UITableView. When I get new data I want the currently visible cells to remain and add the new data above it, much like most Twitter clients does. My load method currently looks like this:
- (void)loadPostsInBackground
{
NSURL *url = [NSURL URLWithString:#"[URL]"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id jsonObject) {
[self createPostsFromDict:jsonObject];
[self.refreshControl endRefreshing];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
NSLog(#"Received an HTTP %d", response.statusCode);
NSLog(#"The error was: %#", error);
}];
[operation start];
}
This works, but it updates the currently visible cells with the new data. So what I want is, get new data, add it above the currently visible cells (or stay at the currently visible cells). What is the best way to do this?
Note: I will require iOS6.
Instead of calling reloadData on the table view. You should call insertRowsAtIndexPaths:withRowAnimation:. Do that after updating the data used by the table view's data source.

Get UIImageView using Afnetworking and put it in an array

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
}

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.