Skip to content

Instantly share code, notes, and snippets.

@oliverfoggin
Created November 7, 2013 09:43
Show Gist options
  • Save oliverfoggin/7351917 to your computer and use it in GitHub Desktop.
Save oliverfoggin/7351917 to your computer and use it in GitHub Desktop.
NSURLConnection download with progress callbacks
This is the place that will get the progress call back and the image.
It must conform to the MyImageDownloaderDelegate protocol
- (void)somFunction
{
MyImageDownloader *downloader = [[MyImageDownloader alloc] init];
[downloader downloadImageFromURL:someUrl withDelegate:self];
}
- (void)downloadFailed
{
NSLog(@"Something went wrong");
}
- (void)progressUpdated:(CGFloat)progress
{
self.progressBar.progress = progress;
}
- (void)imageDownloadFinished:(UIImage *)image
{
self.imageView.image = image;
}
@protocol MyImageDownloaderDelegate <NSObject>
- (void)downloadFailed;
- (void)imageDownloadFinished:(UIImage *)image;
- (void)progressUpdated:(CGFloat)progress;
@end
@interface MyImageDownloader : NSObject
- (void)downloadImageFromURL:(NSURL *)url withDelegate:(id <MyImageDownloaderDelegate>)delegate;
@end
#import "MyImageDownloader.h"
@interface MyImageDownloader () <NSURLConnectionDataDelegate, NSURLConnectionDownloadDelegate>
@property (nonatomic, strong) NSURLConnection *connection;
@property (nonatomic, strong) NSMutableData *receivedData;
@property (nonatomic, weak) id <MyImageDownloaderDelegate> delegate;
@end
- (void)downloadImageFromURL:(NSURL *)url withProgressDelegate:(id <NSURLConnectionDownloadDelegate>)progressDelegate completionDelegate:(id <MyImageDownloaderDelegate>)delegate;
{
self.delegate = delegate;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.receivedData = [NSMutableData data];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startsImmediately:NO];
self.connection.downloadDelegate = self;
[self.connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// check for errors
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// check for errors
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// store the data that comes down
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// get the image and pass to delegate
UIImage *image = [UIImage imageWithData:self.receivedData];
[self.delegate imageDownloadFinished:image];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment