Read Pdf data from webView - ios

I am using both approaches by reading inner HTML content of a webView and by reading AsciiString but in both approaches when i convert it into PDF formate data truncates. Please look my code and tell me where i am wrong.
-(NSData *)createPDFfromUIWebView:(UIWebView*)webView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
[self removeFileByName];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
// NSString *heightStr = (NSString *)[webView stringByEvaluatingJavaScriptFromString:#"getParam();"];
// NSString *heightStr = (NSString *)[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText;"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.all[0].innerHTML"];
NSURL *requestURL = [[self.webViewIphone request] URL];
NSError *error;
NSString *heightStr = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
debug(#"HTml string %#",heightStr);
int height = [heightStr length];
CGFloat screenHeight = webView.scrollView.contentSize.height;
debug(#"%f",screenHeight);
int pages = ceil(height / screenHeight);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
CGRect frame = [webView frame];
for (int i = 0; i < pages; i++) {
// Check to screenHeight if page draws more than the height of the UIWebView
if ((i+1) * screenHeight > height) {
CGRect f = [webView frame];
f.size.height -= (((i+1) * screenHeight) - height);
[webView setFrame: f];
}
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
[webView.layer renderInContext:currentContext];
}
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSData *dataTemp = [NSData dataWithContentsOfFile:documentDirectoryFilename];
return dataTemp;
}

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName =[docPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.xlsx",downloadedfilename]];
[[NSFileManager defaultManager] createFileAtPath:reportName contents:receivedData attributes:nil];
NSURL *url = [NSURL fileURLWithPath:fileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
you can load xlsx,pdf, word document files like above code

This is used for the loading th pdf file into UIWebview.
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];

Related

Combine multiple .pngs into one .pdf

I'm trying to send a .pdf to my app, have it convent each page to a .png, edit photo, then convent them back into one .pdf. I can convert the .pdf to multiple .pngs but trying to convert them back into one .pdf is giving me problems it is exporting each page/image into its own pdf not one. This is just the quick and dirty code where i'm trying to send a .pdf, convert to .pngs, then back to a .pdf with out the editing of the .pngs right now. I've looked at http://code.tutsplus.com/tutorials/generating-pdf-documents--mobile-11265 and Creating a single page pdf file with array of images in iOS? but the images are not in an array... any help would be greatly appreciated.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
NSLog(#"Open URL:\t%#\n"
"From source:\t%#\n"
"With annotation:%#",
url, sourceApplication, annotation);
CGPDFDocumentRef SourcePDFDocument = CGPDFDocumentCreateWithURL((__bridge CFURLRef)url);
size_t numberOfPages = CGPDFDocumentGetNumberOfPages(SourcePDFDocument);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [documentsDirectory stringByAppendingPathComponent:#"temp"];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
[[NSFileManager defaultManager] removeItemAtPath:filePathAndDirectory error:&error];
NSLog(#"other error: %#", error);
[[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error];
}
NSMutableData *pdfFile = [[NSMutableData alloc] init];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfFile);
for(int currentPage = 1; currentPage <= numberOfPages; currentPage ++ )
{
CGPDFPageRef SourcePDFPage = CGPDFDocumentGetPage(SourcePDFDocument, currentPage);
// CoreGraphics: MUST retain the Page-Refernce manually
CGPDFPageRetain(SourcePDFPage);
NSString *relativeOutputFilePath = [NSString stringWithFormat:#"%#/%#%d.png", #"temp", #"photo", currentPage];
NSString *ImageFileName = [documentsDirectory stringByAppendingPathComponent:relativeOutputFilePath];
CGRect sourceRect = CGPDFPageGetBoxRect(SourcePDFPage, kCGPDFCropBox);
UIGraphicsBeginPDFContextToFile(ImageFileName, sourceRect, nil);
UIGraphicsBeginImageContextWithOptions(sourceRect.size, NO, 3);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0.0, sourceRect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextDrawPDFPage (currentContext, SourcePDFPage); // draws the page in the graphics context
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent: relativeOutputFilePath];
CGDataConsumerRef pdfConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfFile);
// The page size matches the image, no white borders.
CGRect mediaBox = CGRectMake(0, 0, sourceRect.size.width, sourceRect.size.height);
CGContextRef pdfContext = CGPDFContextCreate(pdfConsumer, &mediaBox, NULL);
CGContextBeginPage(pdfContext, &mediaBox);
CGContextDrawImage(pdfContext, mediaBox, [image CGImage]);
CGContextEndPage(pdfContext);
CGContextRelease(pdfContext);
CGDataConsumerRelease(pdfConsumer);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
NSString *end = #".pdf";
NSString *start = #"Documents/image";
NSString * timestamp = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970]];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:#"%#%#%#", start, timestamp, end]];
[pdfFile writeToFile:path atomically:YES];
NSLog([NSString stringWithFormat:#"%#%#%#", start, timestamp, end]);
}
return YES;
}
Your problem is that UIGraphicsBeginPDFContextToFile and CGContextRelease(pdfContext) statements should be outside your for loop.
Try this (assuming you've placed all images as a UIImageView on a UIScrollView):
/* CREATE PDF */
self.pdfData = [NSMutableData data];
NSInteger pageHeight = 800;
UIGraphicsBeginPDFContextToData(self.pdfData, CGRectMake(0,0,768,pageHeight), nil);//768*792/612
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
for (int page=0; pageHeight *page < scrollView.frame.size.height; page++)
{
UIGraphicsBeginPDFPage();
CGContextTranslateCTM(pdfContext, 0, -pageHeight * page);
[scrollView.layer renderInContext:pdfContext];
}
UIGraphicsEndPDFContext();
/* EXPORT PDF */
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* fileName = [self genRandStringLength:7];
fileName = [NSString stringWithFormat:#"%#.pdf", fileName];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:fileName];
// instructs the mutable data object to write its context to a file on disk
[self.pdfData writeToFile:documentDirectoryFilename atomically:YES];

e-signing integration makes my multi paged pdf to single page

Am trying to sign my pdf file which is multiple paged, by fetching the signature drawn in UIView to my pdf file, but the problem I face is, after signing the pdf, i could view only the single page of file which is signed, not rest of the pages in my webview.(for eg; if page 3 of my pdf file is signed, i could view only page 3 in my webview, and the pdf file is limited to only page number 3 in my document directory).
Codes used for fetching the signature from document directory to pdf file is,
- (void)viewWillAppear:(BOOL)animated
{
[webView reload];
UIWebView *webView;
webView= [[UIWebView alloc] initWithFrame:CGRectMake(0,44, 320, 460)];
NSString *path1;
path1 = [[NSBundle mainBundle] pathForResource:#"typo_tips" ofType:#"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDirectoryPath;
NSURL *targetURL;
documentDirectoryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"typo_tips.pdf"];
[fileManager copyItemAtPath:path1 toPath:documentDirectoryPath error:&error];
NSLog(#"path1 value is %# \n",path1);
NSLog(#"docu dir path is %# \n",documentDirectoryPath);
if (entered==1)//"entered==1", after save button clicked in signviewcontroller
{
targetURL = [NSURL fileURLWithPath:documentDirectoryPath];
}
else targetURL = [NSURL fileURLWithPath:path1];
if (entered==1)
{
CFURLRef url;
url = (CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:documentDirectoryPath]);
CGPDFDocumentRef myDocument;
myDocument = CGPDFDocumentCreateWithURL(url);
// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL); //(CFURLRef)outputURL
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
NSLog(#"no. of pages in pdf is %d \n",totalPages);
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), CGPDFDocumentGetPage(myDocument, page));
//"page" is current pdf page to be signed
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];// "image.png" is the saved user's signature in document directory
image = [[UIImage alloc] initWithContentsOfFile:filePath];
CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
}
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
}
You have to re-render each page (even the ones not being altered).
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL); //(CFURLRef)outputURL
UIGraphicsPushContext(pdfContext);
int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
NSLog(#"no. of pages in pdf is %d \n",totalPages);
for (int currentPage = 0; currentPage < totalPages; currentPage++)
{
CGPDFContextBeginPage(pdfContext, NULL);
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), CGPDFDocumentGetPage(myDocument, currentPage));
//"page" is current pdf page to be signed
if (page == currentPage)
{
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];// "image.png" is the saved user's signature in document directory
image = [[UIImage alloc] initWithContentsOfFile:filePath];
CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
}
}
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
Found the solution with the help of iPDFDev:
In the for loop have to create a new PDF page for each page in the source file. So move these lines inside the for loop:
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
and also the corresponding cleanup code.
(void)viewWillAppear:(BOOL)animated
{
[webView reload];
UIWebView *webView;
webView= [[UIWebView alloc] initWithFrame:CGRectMake(0,44, 320, 460)];
NSString *path1;
path1 = [[NSBundle mainBundle] pathForResource:#"typo_tips" ofType:#"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDirectoryPath;
NSURL *targetURL;
documentDirectoryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"typo_tips.pdf"];
[fileManager copyItemAtPath:path1 toPath:documentDirectoryPath error:&error];
NSLog(#"path1 value is %# \n",path1);
NSLog(#"docu dir path is %# \n",documentDirectoryPath);
if (entered==1)//"entered==1", after save button clicked in signviewcontroller
{
targetURL = [NSURL fileURLWithPath:documentDirectoryPath];
}
else targetURL = [NSURL fileURLWithPath:path1];
if (entered==1)
{
CFURLRef url;
url = (CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:documentDirectoryPath]);
CGPDFDocumentRef myDocument;
myDocument = CGPDFDocumentCreateWithURL(url);
// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL(url, NULL, NULL);
int totalPages = (int)CGPDFDocumentGetNumberOfPages(myDocument);
NSLog(#"no. of pages in pdf is %d \n",totalPages);
for (int currentPage = 0; currentPage < totalPages; currentPage++)
{
//(CFURLRef)outputURL
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), CGPDFDocumentGetPage(myDocument, page));
//"page" is current pdf page to be signed
if (page == currentPage)
{
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];// "image.png" is the saved user's signature in document directory
image = [[UIImage alloc] initWithContentsOfFile:filePath];
CGRect imageRect = CGRectMake(50, 50, image.size.width, image.size.height);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
}
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
}
CGPDFContextClose(pdfContext);
}
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
}

Viewing a PDF with QLViewController in a WebView

Basically, I want to click a button in my web view that will download a PDF from a remote website and display it with a close/back button. I'm using QLViewController so people can pinch-zoom the PDF, and I'm using PhoneGap 3.0 with XCode 5 to code it.
Here's the code for my plugin that will show the new view with the back button but I can't seem to get the PDF to show. Any ideas?
#import "PDFViewer.h"
#import <Cordova/CDV.h>
#implementation PDFViewer
- (void)loadRemotePdf:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString *website = [command.arguments objectAtIndex:0];
NSString *filename = [command.arguments objectAtIndex:1];
if (website != nil && [website length] > 0) {
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
webView.autoresizesSubviews = YES;
[webView canGoBack];
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// NSURL *myUrl = [NSURL URLWithString:website];
// NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
// [webView loadRequest:myRequest];
// [window addSubview: webView];
NSURL *url = [NSURL URLWithString:website];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
[urlData writeToFile:filePath atomically:YES];
// Create test view controller
QLPreviewController *previewer = [[QLPreviewController alloc] init];
previewer.dataSource = self;
previewer.delegate = self;
// Create navigation controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:previewer];
[window addSubview: [nav view]];
[window makeKeyAndVisible];
}
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
// return result
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
#pragma mark - QLPreviewControllerDataSource
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return 1;
}
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index;
{
NSURL *fileURL = [NSURL fileURLWithPath: filePath];
return fileURL;
}
#end
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simple load it to your web view directly:
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
//Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSString *path = [[NSBundle mainBundle] pathForResource:#"document" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];

Zoom/Pinch the pdf which is loaded in a UIWebView

I have loaded a PDF file in a UIWebView from the resource bundle.
Now, I am not able to zoom/pinch the PDF file.
I found the below 2 relevant links, but none of the answers are marked as correct -
How to zoom webView with pdf file
Enable zooming/pinch on UIWebView
How to make the PDF zoomable/pinchable which has been loaded in a UIWebView from the resource bundle, Will the below solution work ?
Problem with pdf while opening in UIWebView
Thanks for your help.
In your WebView on Interface Builder add check to Scale Page To Fit and you enable a Pinch ZoomIn ZoomOut ;)
Or if you want to lad better your PDF try to Look this code:
- (void)viewDidLoad
{
[super viewDidLoad];
[webView loadRequest:[NSURLRequest requestWithURL:#"http:pdfURL"]];
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourPDFFile" ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
//--------------AND HERE USE SCALE PAGE TO FIT------------------//
[webView setScalesPageToFit:YES];
}
Hope this help you.
//Try like this
NSString *urlstr=#"www.example.com/yy.pdf";
web=nil;
web=[[UIWebView alloc] initWithFrame:CGRectMake(0, 98, 320, 367)];
web.delegate=self;
[self.view addSubview:web];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlstr]]];
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc]
initWithTarget:self action:#selector(handlePinch:)];
pgr.delegate = self;
[web addGestureRecognizer:pgr];
// Target Action
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
recognizer.scale = 1;
}
Before this add UIGestureRecognizerDelegate in .h. Hope it will helps you..
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:documentsDirectory])
{
NSURL *url = [NSURL fileURLWithPath:strFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[webview loadRequest:request];
}

How to retrieve the set of images from server and store it in documents directory in iOS?

I want to retrieve a folder containing 10 images from server, then store that folder in my document directory. I did some code, but when I run it, I am getting the image urls, not the images themselves. Can anyone help me out?
My code:
-(void)viewWillAppear:(BOOL)animated
{
NSMutableData *receivingData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://Someurl.filesCount.php"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivingData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
printf("\n the path is :%s",[path UTF8String]);
NSString *zipPath = [path stringByAppendingPathComponent:#"filesCount.php"];
[receivingData writeToFile:zipPath options:0 error:&error];
NSString *documentsDirectoryPath = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"filesCount"];
NSLog(#"the path %#",documentsDirectoryPath);
}
I made this function in my previous project. You need to pass your imageView and serverUrl, then its automatically show image in your imageView and save image to temp directory, when you want again to fetch same image, then next time it take image from disk.
+(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString* theFileName = [NSString stringWithFormat:#"%#.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
actView.frame = frameToCenter;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *dataFromFile = nil;
NSData *dataFromUrl = nil;
dataFromFile = [fileManager contentsAtPath:fileName];
if(dataFromFile==nil){
dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
}
dispatch_sync(dispatch_get_main_queue(), ^{
if(dataFromFile!=nil){
imgView.image = [UIImage imageWithData:dataFromFile];
}else if(dataFromUrl!=nil){
imgView.image = [UIImage imageWithData:dataFromUrl];
// NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
if(filecreationSuccess == NO){
NSLog(#"Failed to create the html file");
}
}else{
imgView.image = [UIImage imageNamed:#"NO_Image.png"];
imgView.tag = 105;
}
[actView removeFromSuperview];
[actView release];
});
});
}
Try using this code.
NSURL* url = [NSURL URLWithString:#"http://imageAddress.com"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
// do whatever you want with directory or store images.
NSImage* image = [[NSImage alloc] initWithData:data];
}
}];
Use this code to download the image using URL and store in document directory. Iterate the logic for set of images to download and store.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imageURL = #"http://sampleUrl";
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Image1.png"]];
if(image != NULL)
{
//Store the image in Document
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile: imagePath atomically:YES];
}
If you'll showing the images loaded from server on UI, then
try SDWebImageView, can be used with UIButton or UIImageView, very easy and efficient.
example,
[yourImageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Read how to use it?
Okay, now for multiple images, you may need to run a loop, if you've a common base url for all your pictures (on server) something like http://yoururl/server/pictures/1.png will be replace by 2.png 3.png ... n.png, or you get different urls for pictures need to pass that url, you can load it into imageview objects, and later save them into document directory (remember, SDWebImageView by default doing this work for you). You can turn this off too.
P.S. It will load images once and stored into local (in cache) it self, next time when you pass the same image url, it won't load from server and directly load the image from local.

Resources