Download Multiple images using Native functionality IOS - iphone

How to download multiple images and save it to the disk.
The Send request i'm using is below.
for(NSDictionary *image in [data objectForKey:#"Catalogues"])
{
NSString *imurl =[image objectForKey:#"Image_Path"];
NSLog(#"%#",imurl);
NSString *urlstring =imurl;
NSLog(#"demo %#",urlstring);
NSURL *mailurl =[NSURL URLWithString:urlstring];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:mailurl];
NSOperationQueue *ques =[[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:ques completionHandler:^(NSURLResponse *respo, NSData *data, NSError *err) {
UIImage *image = [UIImage imageWithData:data];
UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 150, 150)];
im.image = image;
[self.view addSubview:im];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",documentsDirectory]
any native methods available for multiple images?

you can implement an AsyncImage class like this
in AsyncImage.h file
#import <UIKit/UIKit.h>
#interface AsyncImage : UIView
{
NSURLConnection* connection;
NSMutableData* data;
UIImageView *image;
UIActivityIndicatorView *scrollingWheel;
NSString *imgName;
}
-(void)loadImageFromString:(NSString*)url;
-(void)loadImageFromURL:(NSURL*)url;
-(void)setLocalImage:(UIImage *)localImage;
-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;
#end
in AsyncImage.m file
#import "AsyncImage.h"
#implementation AsyncImage
-(id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
float x = self.bounds.size.width/2;
float y = self.bounds.size.height/2;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
[self addSubview:scrollingWheel];
self.clipsToBounds = YES;
}
return self;
}
-(void)loadImageFromString:(NSString*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
imgName = [[[url componentsSeparatedByString:#"/"] lastObject]retain];
// NSLog(#"imgName=%#",imgName);
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
// NSLog(#"imagePath=%#",imagePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)setLocalImage:(UIImage *)localImage
{
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
image = [[[UIImageView alloc] initWithImage:localImage] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
}
//for URL
-(void)loadImageFromURL:(NSURL*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
NSString *strurl=[NSString stringWithFormat:#"%#",url];
imgName = [[[strurl componentsSeparatedByString:#"/"] lastObject]retain];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData data] retain];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj
{
[data appendData:dataObj];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)theConnection
{
[connection release];
connection=nil;
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
[data writeToFile:imagePath atomically:YES];
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)dealloc
{
[scrollingWheel release];
[super dealloc];
}
-(NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
-(void)cancelConnection
{
if (connection !=nil) {
[connection cancel];
connection=nil;
}
if(data!=nil){
[data release];
data=nil;
}
[scrollingWheel stopAnimating];
}
#end
and at your viewController.m you can import this class and call it like this
AsyncImage *imgBOD = [[AsyncImage alloc] initWithFrame:CGRectMake(10, 46, 70, 70)];
[imgBOD loadImageFromString:[dictData objectForKey:#"image_path"]];
[self.view addSubview:imgBOD];

There is no "native method" for this particular problem.
If you just want to save a list of images to disk, you can improve your approach by not creating UIImages in the first place, just treat the data as binary data and save to disk directly.
In order to maintain low memory foot-print, implement NSURLConnection's delegate methods, and write (append) the image data piece-wise to the destination file as the chunk data arrives in connection:didReceiveData:.
The latter will be best solved by creating a dedicated class which encapsulates NSURLConnection and other related states and is subclassed from NSOperation and employs the asynchronous style implementing NSURLConnection delegates.
You might consider a third party library, too. A warning though: almost all well-known third party network libraries will not let you easily write data in pieces to a file. Per default, they accumulate all received data into one NSMutableData object. That may increase your memory-foot print, since images may be large, and since you can start multiple connections at once.
Also, don't start more than two connections at once.

Related

How to monitor pdf download process in iphone sdk

In my application i need to download pdf file from url.i know how to download pdf file from url and store in local document directory.But i need to show downloading process and i want to know whether download is completed.Please any body give an idea..
Here My code:
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.msy.com.au/Parts/PARTS.pdf"]];
//Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];
Use ASIHTTPRequest for download file. for below code I had used ASIHTTPRequest
float currentProgress;
UILabel *dwnLbl;
UIProgressView * myProgressIndicator;
UIProgressView *progressBar;
#property (nonatomic, retain) ASIHTTPRequest *rqstForAudio;
-(void)viewDidLoad{
self.av=[[UIAlertView alloc] initWithTitle:#"Downloading.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[self.actV setFrame:CGRectMake(125, 60, 37, 37)];
dwnLbl = [[UILabel alloc] initWithFrame:CGRectMake(45, 30, 200, 37)];
dwnLbl.textAlignment = UITextAlignmentCenter;
dwnLbl.font = [UIFont boldSystemFontOfSize:20];
dwnLbl.backgroundColor = [UIColor clearColor];
dwnLbl.textColor = [UIColor whiteColor];
progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[progressBar setFrame:CGRectMake(45, 65, 200, 20)];
progressBar.progress = 0;
[self.av addSubview:dwnLbl];
[self.av addSubview:progressBar];
}
-(void)downLoadBook{
NSString *strAudioURL=#"http://www.msy.com.au/Parts/PARTS.pdf"
// check first locally exists or not
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#/%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
AudioFolder];
NSDictionary *dOfAudios=[NSDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios valueForKey:strAudioURL]) {
} else {
self.av.title = #"Downloading..";
[self.av show];
NSString *pdf = #"bookTitle.pdf";
NSURL *audioURL = [NSURL URLWithString:strAudioURL];
NSString *strPathToDownload=[NSString stringWithFormat:#"%#/%#",[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],pdf];
[self.rqstForAudio setDownloadProgressDelegate:myProgressIndicator];
if(!self.rqstForAudio || [self.rqstForAudio isFinished]) {
self.rqstForAudio=[ASIHTTPRequest requestWithURL:audioURL];
[self.rqstForAudio setDelegate:self];
[self.rqstForAudio setDownloadProgressDelegate:self];
[self.rqstForAudio setAllowResumeForFileDownloads:YES];
[self.rqstForAudio setCachePolicy:ASIUseDefaultCachePolicy];
[self.rqstForAudio setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[self.rqstForAudio setDidFailSelector:#selector(failedToLoad:)];
[self.rqstForAudio setDidFinishSelector:#selector(finishedLoading:)];
[self.rqstForAudio setDownloadCache:[ASIDownloadCache sharedCache]];
[self.rqstForAudio setDownloadDestinationPath:strPathToDownload];
[self.rqstForAudio startAsynchronous];
}
}
}
- (void)failedToLoad:(ASIHTTPRequest*)request {
[self.av dismissWithClickedButtonIndex:0 animated:YES];
NSLog(#"failed to download");
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"MESSAGE" message:#"Failed to Download" delegate:self cancelButtonTitle:RETRY otherButtonTitles:nil, nil];
av.delegate = self;
[av show];
}
- (void)finishedLoading:(ASIHTTPRequest*)request {
NSLog(#"finished loading");
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
NSMutableDictionary *dOfAudios=[NSMutableDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios allKeys].count>0) {
[dOfAudios setValue:[request downloadDestinationPath] forKey:[[request url] description]];
} else {
dOfAudios=[NSMutableDictionary dictionary];
[dOfAudios setValue:[request downloadDestinationPath] forKey:[[request url] description]];
}
[self.av dismissWithClickedButtonIndex:0 animated:YES];
[dOfAudios writeToFile:strPathToAudioCache atomically:YES];
}
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes{
[self setProgress:[myProgressIndicator progress]];
}
- (void)setProgress:(float)progress
{
currentProgress = progress;
if (!progress == 0.0) {
}
if(currentProgress*100 == 100.00){
self.av.title = #"Finishing..";
}
progressBar.progress = currentProgress;
dwnLbl.text = [NSString stringWithFormat:#"%.2f%%",currentProgress*100];
}
EDIT
You can used the NSURLSession method to implement such scenario
NSURLSession
I'd highly recommend taking a look at ASIHTTPRequest for easy file downloading.
where the numbers of the functionality thru you can able to use the download progress.

IPhone - download asynchronous work, but load asynchronous don't

I'm building my custom cell for a table view. I'm trying to load an image from internet and for it, i'm using async download. The image is being downloaded, but it's not showing this image in my cell. I already tried to show in a normal view and it's working fine. It does work too if the image is already downloaded or if I roll the table view and show the cell again. Does anybody knows what's going on?
Code:
DownloadImageManager.m
-(id)initWithImageName:(NSString *)imageAddress{
self = [super initWithFrame:CGRectMake(10, 5, 100, 100)];
if (self){
self.urlString = imageAddress;
av = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
av.frame = self.frame;
[av setBackgroundColor:[UIColor greenColor]];
[self addSubview:av];
[av startAnimating];
[self checkImage];
}
return self;
}
-(void)checkImage{
bool isImageOnSysten = [self isImageOnFileSystem];
if (isImageOnSysten) {
//If image is on the system, loads the image, it's working fine here
NSLog(#"CSantos: isImageOnSysten %# is on system", self.urlString);
} else {
//here is the problem:
[self downloadImage];
}
}
-(void)downloadImage{
NSURL *url = [NSURL URLWithString:self.urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setAllowCompressedResponse:YES];
[request setQueuePriority:NSOperationQueuePriorityLow];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request setTimeOutSeconds:25];
[request setNumberOfTimesToRetryOnTimeout:3];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
NSArray *words = [self.urlString componentsSeparatedByString:#"/"];
NSString *fileName = [words lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
[responseData writeToFile:writablePath options:NSDataWritingAtomic error:&error];
NSLog(#"Write returned error: %#", [error localizedDescription]);
[av stopAnimating];
[av removeFromSuperview];
}
CellForProgram.m
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
textLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 31, 235, 40)] ;
[self.contentView addSubview:textLabel];
photo = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 70, 70)];
[photo setBackgroundColor:[UIColor blueColor]];
photo.image = imagePhoto.image;
[self.contentView addSubview:photo];
}
return self
Cell Caller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CellForProgram *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier] ;
if (cell == nil) {
cell = [[[CellForProgram alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [speaker objectAtIndex:indexPath.row];
DownloadImageManager *imageManager = [[DownloadImageManager alloc] initWithImageName:[images objectAtIndex:indexPath.row]];
[cell.photo setImage:imageManager.image];
return cell;
}
You're not working with the pointers correctly.
When you call [cell.photo setImage:imageManager.image]; and the image does not exists, you're pointing it to nil or to an random memory space.
You need to create a pointer to your cell on the DownloadImageManager class, so that you can update the cell when the image finishes downloading.
Here's what I recommend:
Create a property on DownloadImageManager that points to your custom UITableViewCell class
Do not set the image on the tableView:cellForRowAtIndexPath: selector. Instead, set it directly on the DownloadImageManager.
Here's a simple modification to your code:
Cell Caller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CellForProgram *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier] ;
if (cell == nil) {
cell = [[[CellForProgram alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [speaker objectAtIndex:indexPath.row];
DownloadImageManager *imageManager = [[DownloadImageManager alloc] initWithImageName:[images objectAtIndex:indexPath.row] andCell:cell];
return cell;
}
DownloadImageManager.m
-(id)initWithImageName:(NSString *)imageAddress andCell:(CellForProgram*)cell{
self = [super initWithFrame:CGRectMake(10, 5, 100, 100)];
if (self){
self.urlString = imageAddress;
self.cell = cell;
av = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
av.frame = self.frame;
[av setBackgroundColor:[UIColor greenColor]];
[self addSubview:av];
[av startAnimating];
[self checkImage];
}
return self;
}
-(void)checkImage{
bool isImageOnSysten = [self isImageOnFileSystem];
if (isImageOnSysten) {
//If image is on the system, loads the image, it's working fine here
NSLog(#"CSantos: isImageOnSysten %# is on system", self.urlString);
cell.photo = self.image;
} else {
//here is the problem:
[self downloadImage];
}
}
-(void)downloadImage{
NSURL *url = [NSURL URLWithString:self.urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setAllowCompressedResponse:YES];
[request setQueuePriority:NSOperationQueuePriorityLow];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request setTimeOutSeconds:25];
[request setNumberOfTimesToRetryOnTimeout:3];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
NSArray *words = [self.urlString componentsSeparatedByString:#"/"];
NSString *fileName = [words lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
[responseData writeToFile:writablePath options:NSDataWritingAtomic error:&error];
NSLog(#"Write returned error: %#", [error localizedDescription]);
[av stopAnimating];
[av removeFromSuperview];
cell.photo = self.image;
}
That should get you going. If you need any clarification, be sure to leave a comment and I'll answer shortly.
EDIT: As an alternative, implement an delegate method on the DownloadImageManager...
Add this to the DownloadImageManager.h:
#protocol DownloadImageManagerDelegate <NSObject>
#optional
- (void)DownloadFinished:(DownloadImageManager*)manager;
#end
Instead of the CellForProgram, use the DownloadImageManager protocol, with this constructor as example:
-(id)initWithImageName:(NSString *)imageAddress andDelegate:(DownloadImageManagerDelegate*)delegate
And change your implementation of requestFinished: like so:
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
NSArray *words = [self.urlString componentsSeparatedByString:#"/"];
NSString *fileName = [words lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
[responseData writeToFile:writablePath options:NSDataWritingAtomic error:&error];
NSLog(#"Write returned error: %#", [error localizedDescription]);
[av stopAnimating];
[av removeFromSuperview];
if ([delegate respondsToSelector:#selector(DownloadFinished:)]) {
[delegate DownloadFinished:self];
}
}
Then, make your cell implment the given protocol, like so:
- (void)DownloadFinished:(DownloadImageManager*)manager {
this.photo = manager.image;
}
This way you can keep your functionality on DownloadImageManager, as you want it.
I told I wouldn't need to do this kind of change on DownloadImageManager! But thanks for trying to help, it helped me in other stuff I was stucked!
CellForProgram.m
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
textLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 31, 235, 40)] ;
[self.contentView addSubview:textLabel];
imagePhoto = [[DownloadImageManager alloc] initWithImageName:imageAdress.text];
[self.contentView addSubview:imagePhoto];
}
return self
}
DownLoadImageManager.m: add this method
-(void)changeImage:(NSString *)newImage{
self.urlString = newImage;
[self checkImage];
}
Cell Caller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CellForProgram *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier] ;
if (cell == nil) {
cell = [[[CellForProgram alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [speaker objectAtIndex:indexPath.row];
[cell.imagePhoto changeImage:[images objectAtIndex:indexPath.row]];
return cell;
}

i want to save my pdf into my iphone, pdfs url are with me through parsing

I have parsed my xml and i got some images and their corresponding urls of pdf from server.so whenever i click on image i have their corresponding url of pdf.I am giving an alertView on click of images and when user select the download button of alertView it should download the pdf from url into my iphone device
CODE:-
#implementation SecondViewController
#synthesize scrollView,receivedData;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
[myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
myIndicator.hidesWhenStopped = YES;
[myIndicator startAnimating];
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"iphone_landscape.png"]];
self.view.backgroundColor = background;
[background release];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:150.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [[NSMutableData data] retain];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
int x=20,y=50;
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 45,320, 480)];
scrollView.contentSize = CGSizeMake(320,5000);
scrollView.showsVerticalScrollIndicator = YES;
for (Litofinter *lito in appDelegate.bookArray) {
if([appDelegate.currentButtonPressed isEqualToString:lito.cName])
{
NSLog(#"Count == %d ===",[lito.productsArray count]);
for (Products *prod in lito.productsArray) {
NSString * urlString = [prod.thumbnail stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL * imageURL = [NSURL URLWithString:urlString];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
[myIndicator stopAnimating];
[myIndicator removeFromSuperview];
UIButton *imageButton = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
[imageButton setFrame:CGRectMake(x, y, 150, 200)];
[imageButton setImage:image forState:UIControlStateNormal];
[imageButton setTitle:prod.pdf forState:UIControlStateNormal];
[imageButton addTarget:self action:#selector(onTapBook:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:imageButton];
x = x + 150;
if(x >300)
{
y = y +250;
x = 20;
}
}
}
}
[self.view addSubview:scrollView];
[connection release];
[receivedData release];
}
-(void)onTapBook:(id)sender{
UIButton *button = (UIButton *) sender;
appDelegate.currentBookPressed = [button currentTitle];
// viewController2 = [[PdfShowViewController alloc]initWithNibName:#"PdfShowViewController" bundle:nil];
// [self presentModalViewController:viewController2 animated:YES];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Ver Catalogo!" message:#"" delegate:self cancelButtonTitle:#"Cancelar" otherButtonTitles:#"Ver on-line",#"Descargar",nil];
[alert show];
/*[NSString stringWithFormat:#"%#",appDelegate.currentBookPressed] */
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Ver on-line"])
{
// i will show the pdf online here
}
else if([title isEqualToString:#"Descargar"])
{
// what to write to download the pdf
}
}
-(IBAction)onTapBack{
[self dismissModalViewControllerAnimated:YES];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
[scrollView release];
}
#end
I would do it with NSURLConnection and then I would reuse same code above, because you have it already declared properly.
Save data to NSData and then with writeToFile save it to main bundle.
So here is some more explanation how I would do it.
There are several ways to do it.
Here is how to do it with NSData
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]]; [myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
Also you can use ASIHTTPRequest library which has been discontinued by author, but still works like it should.
ASIHTTPRequest *myDownloadRequest = [ASIHTTPRequest requestWithURL:fileUrl];
[request setDownloadDestinationPath:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"]];
But maybe easiest way of all because as I can see you have displayed pdf already, so it's contents are in receivedData is just to call
[receivedData writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
So actually you can reuse code that you have already wrote in viewDidLoad, replace url if necessary and after connection is closed save file to disk.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:150.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [[NSMutableData data] retain];
}

AFGetImageOperation in OpenFlow

What's the correct way to implement AFGetImageOperation for OpenFlow.
AFGetImageOperation *getImageOperation = [[AFGetImageOperation alloc] initWithIndex:i viewController:self];
getImageOperation.imageURL = [NSURL URLWithString:aImage.imageURL];
[loadImagesOperationQueue addOperation:getImageOperation];
[getImageOperation release];
aImage.imageURL has the requested image URL but unsure where the retrieved image is stored?
Thanks
Images are not cached. It fetches the image again and again.
You can cache the image using following methods..
-(NSString *) md5String
{
NSString *md5 = [Utilities md5String:[imageURL absoluteString]];
return md5;
}
-(void) storeImage:(UIImage *)image AtPath:(NSString *)path
{
NSFileManager *manager = [NSFileManager defaultManager];
if([manager fileExistsAtPath:path])
{
[manager removeItemAtPath:path error:nil];
}
NSData *data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:NO];
}
//TODO: //We need to cehck the expiry date as well..
//-(UIImage *) imageFromPath:(NSString *)path Expiry:()
-(UIImage *) loadImageFromPath:(NSString *)path
{
UIImage *image = nil;
NSFileManager *manager = [NSFileManager defaultManager];
if([manager fileExistsAtPath:path])
{
image = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
}
return image;
}
-(NSString *) cachedImagePath
{
NSString *md5 = [self md5String];
NSString *cachedFilePath = [[Utilities applicationCacheDirectory] stringByAppendingPathComponent:md5];
return cachedFilePath;
}
- (void)main {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
if (imageURL) {
UIImage *photo = nil;
NSString *cachedFilePath = [self cachedImagePath];
UIImage *image = [self loadImageFromPath:cachedFilePath];
if(image)
{
photo = image;
}
else
{
NSData *photoData = [NSData dataWithContentsOfURL:imageURL];
photo = [UIImage imageWithData:photoData];
[self storeImage:photo AtPath:cachedFilePath];
}
// Create a UIImage from the imageURL.
if (photo) {
[mainViewController performSelectorOnMainThread:#selector(imageDidLoad:)
withObject:[NSArray arrayWithObjects:photo, [NSNumber numberWithInt:photoIndex], nil]
waitUntilDone:YES];
}
} else {
// Load an image named photoIndex.jpg from our Resources.
NSString *imageName = [[NSString alloc] initWithFormat:#"place_holder_bg.png", photoIndex];
UIImage *theImage = [UIImage imageNamed:imageName];
if (theImage) {
[mainViewController performSelectorOnMainThread:#selector(imageDidLoad:)
withObject:[NSArray arrayWithObjects:theImage, [NSNumber numberWithInt:photoIndex], nil]
waitUntilDone:YES];
} else
NSLog(#"Unable to find sample image: %#", imageName);
[imageName release];
}
[pool release];
}

Displaying an Image from URL Objective C

Is there any way of achieving the following that avoids using "initWithData" ? (Just in case you are curious, initWithData is getting my app flagged by Apple as using an illegal API sigh).
NSData * imageData = [NSData dataWithContentsOfURL : [NSURL URLWithString : [details image]]];
picture = [[UIImage alloc] initWithData:imageData];
Many thanks,
Martin
if you want to get the image data,then initialize a UIImage using that data:
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://Serverurl/pic007.jpg"]];
cell.image = [UIImage imageWithData: imageData];
[imageData release];
First of all, you should do this asynchronously so that your thread won't block. Here is the code for the class:
#implementation AsyncImageView
+ (void)initialize {
[NSURLCache setSharedURLCache:[[SDURLCache alloc] initWithMemoryCapacity:0
diskCapacity:10*1024*1024
diskPath:[SDURLCache defaultCachePath]]];
}
- (void)setImageFromURL:(NSURL *)url{
/* Put activity indicator */
if(!activityIndicator) {
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect frame = [activityIndicator frame];
frame.origin.x = (self.frame.size.width - frame.size.width)/2;
frame.origin.y = (self.frame.size.height - frame.size.height)/2;
activityIndicator.tag = 9999;
activityIndicator.frame = frame;
[self addSubview:activityIndicator];
[activityIndicator startAnimating];
}
/* Cancel previous request */
if(fetchImageConnection) {
[fetchImageConnection cancel];
}
[imageData release];
/* Start new request */
NSURLRequest *req = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
imageData = [NSMutableData new];
fetchImageConnection = [NSURLConnection connectionWithRequest:req
delegate:self];
[fetchImageConnection retain];
}
- (void)setImageFromDisk:(UIImage *)img {
self.image = img;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[imageData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if(connection == fetchImageConnection) {
self.image = [UIImage imageWithData:imageData];
[[NSNotificationCenter defaultCenter] postNotificationName:#"imageDownloaded" object:self];
[activityIndicator removeFromSuperview];
[imageData release];
[activityIndicator release];
activityIndicator = nil;
imageData = nil;
fetchImageConnection = nil;
}
[connection release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
NSLog(#"error: %#", error);
}
#end
Try this code:
NSString *imgString = #"https://www.lockated.com/system/attachfiles/documents/000/002/489/original/ZPMHaJUSjAGnUrVuOmbqoExRMryvcySVOIkJQMivnAntvpmpYd.jpg?1501833649";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgString]];
accountImageView.image = [UIImage imageWithData: imageData]; // accountImageView is imageView
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://Serverurl/pic007.jpg"]];
self.image=nil;
UIImage *img = [[UIImage alloc] initWithData:receivedData ];
self.image = img;
[img release];
I hope this code will help you!!