Rectangle 27 17

The technique you want to implement is called lazy loading. Since you are using AFNetworking it will be easier to implement this in your case. Each of your collection view cell needs to have a UIImageView to display the image. Use the UIImageView+AFNetworking.h category and set the correct image URL by calling method

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // ....

    [cell.imageView setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    // ...
    return cell;
}

Placeholder is the image which will be displayed until required image is downloaded. This will simply do the required job for you.

Note: By default, URL requests have a cache policy of NSURLCacheStorageAllowed and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use setImageWithURLRequest:placeholderImage:success:failure:.

Also, for you reference, if you want to implement lazy loading of images yourself, follow this Apple sample code. This is for UITableView but same technique can be used for UICollectionView as well.

However, when i implement this, the collectionview is quite hacky when scrolling. is this method completely asynchronous ? Any idea how to make the scrolling of my collectionview less hacky? =)

@Eyeball Yes this is completely asynchronous. Are there any other operations you are performing like FileIO in cellForItemAtIndexPath? Any operations that would cause a noticeable pause in the main thread?

You can use the same category function which will first lookup in the AFNetworking cache, if found will use local copy, if not, it will download fresh copy. Your app caches directory will be wiped off if device receives low memory warning, requiring you to re-download and manage the caching. Instead let AFNetworking do it efficiently :)

Also AFNetworking will handle resource refresh when caching, Ex it will check the Etag for cached image. If image provider changes the image resource at the same url then AFNetworking will download the modified resource and replace for cached URL.

ios - UICollectionView - Downloading images and effective reloading of...

ios objective-c cocoa-touch afnetworking uicollectionview
Rectangle 27 2

There will be issue because of Async call and ReUsability. Lets say your Image at IndexPath 1 is loading image but it is still taking time to download and meanwhile user scrolled down at some another index i.e. 15 and Internally the same cell of Index 1 is alloted to Index 15 and Image of cell 1 will be displayed in Cell 15 if you have not managed to handle previous calls for same instance of cell. Thats why its Better to use some caching library like SDWebImage(As @SeanLintern88 said) or AFNetworking's UIImageView Category

Event if you wanted to do this, then better is to go with subclassing, it will help you to manage the Calls and Its termination.

In your case the Loading of Image might be because of Size of actual image that you are loading from server. CDN kind of service provide some easy to implement techniques to serve different size of images as per the request. So even If User has uploaded 1200x1200 sized image but on list screen you can fetch its 120x120 sized image, This helps is faster loading as well as it will save Physical Memories.

"Image of cell 1 will be displayed in Cell 15" can you explain more about this please , What i though is each row as an index so if he scroll to index 15 it will show postimg[15] in cell 15 after it loads postimg[1]

As I said, you are using the same LocationImageData downloaded to create Image and assign it in UIImageView, so if Respons of some previous call comes to late then its data will be populated on the image even your current cell is not that one. Either you should put a Check condition whether the downloaded data is for the current IndexPath or not.

ios - UIImage from url takes long time to load swift - Stack Overflow

ios swift uitableview uiimage
Rectangle 27 1

To enable the app while getting the images from server and disable block while loading the images try to use UIImageView+AFNetworking library to load the image from server asynchronously AFNetworking

NSMutableArray* imageViews= [[NSMutableArray alloc]init];
for (int i = 0; i < [publicDataArray count]; i++)
{
    NSDictionary *dict = [publicDataArray objectAtIndex:i];
    for(NSString *key in dict)
    {
        NSString *imageUrl = [[dict objectForKey:@"photo"] objectForKey:@"url"];

        UIImageView *myImage = [[UIImageView alloc] init];

        [myImage setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage    imageNamed:@"PlaceHolder.png"]];

        [imageViews addObject:myImage];
    }   
}

NSLog(@"publicDataArray count %lu",(unsigned long)[publicDataArray count]);

[carousel setImages:[NSArray arrayWithArray:imageViews]];

// Add carousel to view
[self.view addSubview:carousel];

thanks! I do get an error with Instance Method - setImageWithUrl:placeholderImage:' not found (return type defaults to id'

My mistake; I added that now. The line [carousel setImages:[NSArray arrayWithArray:imageViews]]; triggers a uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView length]: unrecognized selector sent to instance. Is that a bounds issue with the array. I'm unsure what that is. thanks again :)

make sure to deal with images array inside the carousel when you measure the length because this error say that you are trying to measure length of single imageview

thanks again. I added the code for the carousel class above. I spent a couple hours on it but don't see how the length property is coming into play.

ios - Looping through data from an NSArray and extracting the UIImage ...

ios objective-c uiimage nsarray
Rectangle 27 3

AFNetworking provides async image loading into a UIImageView with placeholder support. It also supports async networking for working with APIs in general.

iphone - Can I load a UIImage from a URL? - Stack Overflow

iphone uiimage uiimagepickercontroller
Rectangle 27 0

Don't think twice. For any networking operation, use AFnetworking and for any Image web loading use SDWebImage

ios - how to download news faster? - Stack Overflow

ios objective-c networking downloading
Rectangle 27 0

SDWebImage is much much faster then UIImage + AFNetworking .

In UITableViewCell you can see the significant difference in performance . It was taking a hell lot of time in AFNetworking and the code is also too long . SDWebImage is much faster and short .

ios - Is there a big advantage to using SDWebImage over AFNetworking f...

ios objective-c afnetworking afnetworking-2 sdwebimage
Rectangle 27 0

Yes, it is asynchronous. You can use the callback blocks if you want to process the image, e.g.:

[imageView setImageWithURLRequest:request
                 placeholderImage:nil
                          success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                              // do image resize here

                              // then set image view

                              imageView.image = image;
                          }
                         failure:nil];

If you're just looking to cache in memory for performance reasons, then the answer is an unequivocal yes. It employs a NSCache (which will be emptied upon memory pressure). As an aside, it will cache the image as retrieved, not reflecting any resizing you do after the fact.

If you're looking to cache in persistent storage (i.e. a cache that will persist even if you terminate app and restart it), that question is a little less clear. AFNetworking claims to support disk caching through its use of NSURLCache, but I have had problems getting that to work on iOS. If you need persistent storage caching, I might suggest a variety of other UIImageView categories, such as SDWebImage.

Anyway, for the AFNetworking official line on caching, I might refer you to the Caching discussion in the AFNetworking FAQ.

If you want an activity indicator view, you can:

UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicatorView.center = self.imageView.center;
[self.view addSubview:activityIndicatorView];
[activityIndicatorView startAnimating];

[imageView setImageWithURLRequest:request
                 placeholderImage:nil
                          success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                              [activityIndicatorView removeFromSuperview];

                              // do image resize here

                              // then set image view

                              imageView.image = image;
                          }
                          failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                              [activityIndicatorView removeFromSuperview];

                              // do any other error handling you want here
                          }];

Nice. I just need for performance, not persistent cache.

Another question: placeholderImage could be a activityindicator GIF?

@DanielCampos Instead of animated GIF, I might suggest UIActivityIndicatorView. See revised answer.

Hi Rob, I understood everything and it's awesome. But in my case, there will be a lot of UIImageViews, something like Instagram app, and I want an activityindicador in the middle of all UIImageViews, for that I think the gif is a most effective solution. Do you agree?

@DanielCampos Personally, I'd probably stick with UIActivityIndicatorView, but it's up to you. If I really wanted some non-standard look to my spinner, I might be inclined to use the UIImage methods animatedImage..., but try both ways and see what works best for you.

ios - Loading image with AFNetworking - Resizing - Stack Overflow

ios objective-c uiimageview afnetworking
Rectangle 27 0

UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS YOu Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
UIImage
- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
    {
        //CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);

        CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
        UIImage *cropped = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);

        return cropped;
    }

Here you get Croped Image that return by above method;

And also Use following method for specific hight and width with image for Resizing UIImage:

+ (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
{
    CGSize newSize = CGSizeMake(width, height);
    float widthRatio = newSize.width/image.size.width;
    float heightRatio = newSize.height/image.size.height;

    if(widthRatio > heightRatio)
    {
        newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
    }
    else
    {
        newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
    }


    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

This method return NewImage, with specific size that you want.

This method is awesome. But it is needed to use the "+" instead of the "-" at the start of the method declaration?

then change sign and you need to call this method by class name its call static method

The "+" is a public function, and "-" is a private function.

@olamarche close, '+' denotes a CLASS METHOD while '-' signifies an INSTANCE METHOD. A class method we all know & love [NSString stringWithFormat:] (Notice it is called on the class, NSString) where an instance method for NSString would be [instanceOfString characterAtIndex:] would be called on an instance of NSString to get the character at the index of that specific string.

Hello @iPatel I've little question arise in my mind.How can I use your code if I'm getting string from remote server?Please help me,I'm stuck with it

ios - Loading image with AFNetworking - Resizing - Stack Overflow

ios objective-c uiimageview afnetworking
Rectangle 27 0

AFNetworking is very good for asynchronous loading and even comes with functionality for handling image loading (of Album Artwork, for example). The github repo includes sample code.

iphone - UITableView loading images after app loads - Stack Overflow

iphone ios cocoa-touch uitableview uikit
Rectangle 27 0

Often one will download the JSON data up front, but defer the loading of the images, not downloading them until required by the UI (a pattern known as "lazy loading"). One particularly elegant way of handling that is to use a UIImageView category that performs just-in-time asynchronous image retrieval (SDWebImage is a pretty good implementation; if you're using AFNetworking, it has one, too). For both of those, you'd simply do something like:

[self.imageView setImageWithURL:url];

And that will retrieve the image asynchronously, cache the image in case your UI needs it again, etc. Also, if you use this within a tableview with cell reuse, it will cancel old requests for prior cells for which the download hasn't yet finished to make sure that requests for the images for visible cells don't get backlogged behind a bunch of old requests that the user may no longer care about, etc.

Sometimes, though, you really want to retrieve everything up front (e.g. you're downloading the content for a magazine that you want to make available for reading offline).

In that case, rather than having the model, itself, do the retrieval, you might have a separate data controller which will download and parse the results. If you need to inform the UI when this is done, you might employ local notifications, to do so.

While this latter pattern might seem appealing at first glance, it has numerous disadvantages. If, for example, the user is on their cellular connection, you might spend a lot of bandwidth downloading images that the user might not immediately need, consuming the user's data plan and battery in the process. So you might want to only do this if (a) you really need everything up front for offline usage; and (b) you're ok with the resource (data plan and battery consumption) drain this entails.

Hi Rob, it has to be the latter. I'm used to using the first approach you suggested but the client requires that all content is downloaded upfront, then the app will be mostly used without a connection. I'm just not sure how to monitor all the images downloading asynchrony and how to know when they have all finished downloading.

@DarrenFindlay: can you package the images server side into one archive?

@DarrenFindlay I'd personally use an NSOperation-based download mechanism (either roll your own (like this) or, better, use AFNetworking) and then create a final "completionOperation" which has dependencies for all of the individual downloads, and when the downloads are done, your "completionOperation" will fire off.

ios - Should my model objects be responsible for downloading their own...

ios design model-view-controller
Rectangle 27 0

AFNetworking would be perfect for your needs. It has its own UIImageView category that handles asynchronous image loading very smoothly. Give it a try.

He would replace his code with AFNetworking's code. The AFNetworking code is fantastic. - And if you don't know how to use AFNetworking, this is not the place to ask. You seem to lack the fundamental skills required for coding in iOS, and you'd be better off doing a course (such as those provided for free on iTunes U) or learning from a book.

I know AFNetworking is a fantastic Framework, i'm not asking how to use it. I just asking how AFNetworking will speed up his code?

ios - How to download many images with AFNetworking? - Stack Overflow

ios iphone ios6 afnetworking sdwebimage
Rectangle 27 0

Your problem is most likely the dispatch_sync back to the main queue creating a deadlock when the image has finished loading.

The easiest way to solve that is to simply replace your dispatch_sync with dispatch_async.

if(image) {
    [[TMCache sharedCache] setObject:image forKey: [imageUrl absoluteString]];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.image = image;
    });
}

I don't see any reason to use a dispatch_sync there since you're already in a dispatch_async block; this shouldn't have any negative effects on your code. If fact, you should usually try to avoid using dispatch_sync if at all possible, precisely for the issue you're running in to here.

when it hangs, have you paused your application in Xcode to see what it's trying to execute?

when I pause the debugger it places on semaphore_wait_trap, I have 71 threads spawned...I'm pretty sure it is a deadlock, and of course I'm sure I'd rather be using AFNetworking to make myself a favour... that said I'd like to understand what has been my mistake.

That definitely sounds like a deadlock. Is your main thread/queue waiting on semaphore_wait_trap, or is it just the other threads? Do you have any other GCD code in your app that could be deadlocking ?

Apparently every thread is on semaphore_wait_trap, plus... looks like I'm having other networking with Parse framework presumably caused by this.

objective c - UIImageView category to download images with GCD fails w...

objective-c uiimageview grand-central-dispatch
Rectangle 27 0

SDWebImage has much more control over image caching. It can cache to disk or memory.

AFNetworking relies on NSURLCache to persist images between app launches (and it's not very reliable), but it's great if you just need to cache during one run.

Both solutions cache a UIImage object in memory during the lifetime of the app. This is important because caching the NSData representation isn't fast enough to load images smoothly when scrolling through a table view.

Summary: AFNetworking's solution is simpler and will work for most use cases. If you need finer control, or disk caching, use SDWebImage instead of modifying AFNetworking's implementation.

ios - Is there a big advantage to using SDWebImage over AFNetworking f...

ios objective-c afnetworking afnetworking-2 sdwebimage
Rectangle 27 0

If you look at the code, you can see that the category UIImageView+AFNetworking cache the UIImage (using NSCache and the urlRequest as the key). The cache isn't written to disk though.

ios - Is there a big advantage to using SDWebImage over AFNetworking f...

ios objective-c afnetworking afnetworking-2 sdwebimage
Rectangle 27 0

You're right, the AFNetworking category implementation (UIImageView+AFNetworking) is bare-bones.

But you're missing AFImageResponseSerializer, which validates and decodes images and provides a few options for handling them. (In the old 1.x version of AFNetworking, this functionality is in AFImageRequestOperation.)

Similarly, you're only looking at the very basic implementation of SDWebImage. There are a LOT of options here, so I suggest you review some of the other classes, but at the most basic level, you can get a UIImage like this:

SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
                 options:kNilOptions
                 progress:^(NSUInteger receivedSize, NSUInteger expectedSize)
                 {
                     // update a progress view
                 }
                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
                 {
                     if (image)
                     {
                         // Do something with the image; cacheType tells you if it was cached or not.
                     }
                 }];

What if you hand it to another class and the UIImage hasn't loaded yet?

Well, it's all loaded asynchronously, so the completion block wouldn't get called until the UIImage was loaded.

ios - Why do all the async image loading (SDWebImage, AFNetworking) li...

ios objective-c uiimageview afnetworking sdwebimage
Rectangle 27 0

To enable the app while getting the images from server and disable block while loading the images try to use UIImageView+AFNetworking library to load the image from server asynchronously AFNetworking

NSMutableArray* imageViews= [[NSMutableArray alloc]init];
for (int i = 0; i < [publicDataArray count]; i++)
{
    NSDictionary *dict = [publicDataArray objectAtIndex:i];
    for(NSString *key in dict)
    {
        NSString *imageUrl = [[dict objectForKey:@"photo"] objectForKey:@"url"];

        UIImageView *myImage = [[UIImageView alloc] init];

        [myImage setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage    imageNamed:@"PlaceHolder.png"]];

        [imageViews addObject:myImage];
    }   
}

NSLog(@"publicDataArray count %lu",(unsigned long)[publicDataArray count]);

[carousel setImages:[NSArray arrayWithArray:imageViews]];

// Add carousel to view
[self.view addSubview:carousel];

thanks! I do get an error with Instance Method - setImageWithUrl:placeholderImage:' not found (return type defaults to id'

My mistake; I added that now. The line [carousel setImages:[NSArray arrayWithArray:imageViews]]; triggers a uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView length]: unrecognized selector sent to instance. Is that a bounds issue with the array. I'm unsure what that is. thanks again :)

make sure to deal with images array inside the carousel when you measure the length because this error say that you are trying to measure length of single imageview

thanks again. I added the code for the carousel class above. I spent a couple hours on it but don't see how the length property is coming into play.

ios - Looping through data from an NSArray and extracting the UIImage ...

ios objective-c uiimage nsarray
Rectangle 27 0

AFNetworking is very good for asynchronous loading and even comes with functionality for handling image loading (of Album Artwork, for example). The github repo includes sample code.

iphone - UITableView loading images after app loads - Stack Overflow

iphone ios cocoa-touch uitableview uikit
Rectangle 27 0

I got it, the code was fine it was an issue with the naming of the parameters, here it is:

// publish text and image
-(void)publishTextAndImage:(NSString*)resultDisplay and:(NSString*)subject with:    (NSString*)nonce
{
imageData = UIImageJPEGRepresentation(selectedImage, 0.7); // create a data object from     selected image

NSString *myUUID = [[NSUUID UUID] UUIDString]; // create a UUID
NSString *formatString = [NSString stringWithFormat:@"<img src=\"/wp-    content/uploads/%@\"/>",myUUID];
NSString *contentString = [formatString stringByAppendingString:resultDisplay];
NSString *moodString = [NSString stringWithFormat:@"%d",self.moodNumber];

NSDictionary *parameters = @{@"title":subject,
                         @"content":contentString,
                         @"status":@"publish",
                         @"author":@"wordpress",
                         @"user_password":@"xrayyankee",
                         @"nonce":nonce,
                         @"categories":moodString};

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager POST:@"http://thrills.it/?json=posts/create_post" 
 parameters:parameters 
 constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
 {
 if (selectedImage)
 {
     [formData appendPartWithFileData:imageData name:@"attachment" fileName:myUUID     mimeType:@"image/jpeg"];
 }

} 
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
 NSLog(@"JSON: %@", responseObject);

}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
 NSLog(@"Error: %@", error);
}];

so basically I removed the "attachment" parameter from the parameters dictionary and changed the name of the appended imageData to @"attachment". it was an issue of wordpress json api being very picky (:

ios - Loading an Image with AFNetworking 2.0 - Stack Overflow

ios objective-c afnetworking-2
Rectangle 27 0

As stack says, you should be loading the images asynchronously, and there are wonderful UIImageView categories that make this really easy to do, namely the category in SDWebImage or in AFNetworking. These UIImageView categories not only load images asynchronously, but also do caching, cancel network operations if necessary, etc. It takes a lot of code if you do this properly yourself (capturing all of those features I just enumerated), but it's really easy if you use one of these categories.

#import "UIImageView+WebCache.h"

and then:

Or, if using AFNetworking:

#import "UIImageView+AFNetworking.h"

and

[cell.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:url] placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:nil failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"%s: setImageWithURLRequest error: %@", __FUNCTION__, error);
}];

uicollectionview - iOS Collection View Scrolling Lags - Stack Overflow

ios uicollectionview
Rectangle 27 0

Adding more to Teodor's answer, using AFNetworking framework will help your life. It works with block based methods. More helpful, it has AFImageRequestOperation, a specific class for downloading and processing images, and UIImageView+AFNetworking, that can help you even more loading remote images asynchronously.

uitableview - How to display the images from url in tableview in iPhon...

iphone uitableview ios5