Hi I am getting single image from server using url in iOS.
my code is like this
- (IBAction)overlaysClicked:(id)sender
{
NSLog(#"overlays Clicked");
request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon/ov1.png"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"image.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon/ov1.png"]];
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
self.overlayImgView.image=img;
}
To get multiple images from server my code like this
NSURL *myUrl = [NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon.zip"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
myData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self startImmediately:YES];
//my Array is like this in viewDidload
self.overlaysImgsArray = [[NSMutableArray alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon.zip"]];
NSLog(#"urls is %#",overlaysImgsArray);
for (int i=0; i<[overlaysImgsArray count]; i++)
//download array have url links
{
NSURL *URL = [NSURL URLWithString:[overlaysImgsArray objectAtIndex:i]];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:URL];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if([data length] > 0 && [[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"])
{
//make your image here from data.
UIImage *imag = [[UIImage alloc] initWithData:[NSData dataWithData:data]];
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [array objectAtIndex:0];
NSString *imgstr=[NSString stringWithFormat:#"%d",i];
NSString *pngfilepath = [NSString stringWithFormat:#"%#sample%#.png",docDir,imgstr];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(imag)];
[data1 writeToFile:pngfilepath atomically:YES];
}
else if ([data length] == 0 && [[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"])
{
NSLog(#"No Data!");
}
else if (![[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"]){
NSLog(#"Error = %#", error);
}
}];
}
}
But this is not working for me please anybody suggest me how to get multiple images from server using one url which contains all the images. Please anybody
thank you in advance
In your case you can try like this
first you need to save all the 10 image in directory and the fetch one by one as your requirement .this code save all image from your url
try this
- (IBAction)overlaysClicked:(id)sender {
//Note all your image saved with ov1.png,ov2.png......& so .
for (int i=1; i<=10; i++) {
NSString *st2=#"ov";
NSString *st1=#"http://sukhada.co.in/img/overlays/neon/ov";
NSString *imageN=[st2 stringByAppendingString:[NSString stringWithFormat:#"%d",i]];
NSString *imgNameforkey=[imageN stringByAppendingString:#".png"];
NSString *url=[st1 stringByAppendingString:[NSString stringWithFormat:#"%d",i]];
NSString *imgname=[url stringByAppendingString:#".png"];
NSLog(#" all=%#",imgname);
NSLog(#"overlays Clicked");
request = [NSURLRequest requestWithURL:[NSURL URLWithString:imgname]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imgname];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgname]];
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
NSLog(#"imgs %#",img);
// self.overlayImgView.image=img;
}
}
here you can see all image saved
fetch the image
using loop or with name
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
imagePath= [imagePath stringByAppendingPathComponent:#"ov1.png"];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *img = = [UIImage imageWithData:data];
download a zip file from url and save it .use this code inside the button action. no need for loop now. try this
- (IBAction)overlaysClicked:(id)sender {
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSLog(#"Beginning download");
NSString *stringURL = #"http://sukhada.co.in/img/overlays/neonra.zip";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSLog(#"Got the data!");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSLog(#"Saving");
NSString *dataPath = [path stringByAppendingPathComponent:#"img.zip"];
dataPath = [dataPath stringByStandardizingPath];
[urlData writeToFile:dataPath atomically:YES];
});
}
and check you will get img.zip file
Related
I am new in iOS and while I scroll PDF file on UIWebView it hangs. I am using code like this
String = [String stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *urlAddress = String;
NSURL *url = [[NSURL alloc] initWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSString *urlToDownload = String;
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *Title=TranningTitle;
Title = [Title stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *format=#".pdf";
NSString *finalString=[NSString stringWithFormat:#"%#%#",Title,format];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,finalString];
NSLog(#"File Path =%#",filePath);
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
[Showwebview loadRequest:requestObj];
});
}
});
It mostly hang on iPad.
Try using Quicklook framework instead. Click here for sample code
My question is what format the image is saved, if is dat or jpg. This is the code that i used:
NSString * urlImage = .....;
NSString * _folderPath = .....;
NSString * imageName = [[urlImage componentsSeparatedByString:#"/"] lastObject];
NSString * jpegPath = [NSString stringWithFormat:#"%#%#",_folderPath,imageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:jpegPath])
{
NSURL *url = [NSURL URLWithString:urlImage];
//Download image
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
//Save image
NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data writeToFile:jpegPath atomically:YES];
}
Following is piece of code for save .jpg image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path = [docs stringByAppendingFormat:#"/image1.jpg"];
NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageView.image, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];
You should use
stringByAppendingPathComponent method to create or get exact valid path
Use this way:
NSString * jpegPath = [_folderPath stringByAppendingPathComponent:imageName];// [NSString stringWithFormat:#"%#%#",_folderPath,imageName];
I want save json file from server each time, when user have internet connection to use it when iPhone doesnt have internet connection. But it doesn't working. Here is my code:
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://volodko.info/ic/json.php";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
try this . . .
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://volodko.info/ic/json.php";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"data.json"];;
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
This works for me. Read the AFJSONRequestOperation guide. The code also checks if the json-file already have been cached.
NSString *path = #"http://volodko.info/ic/json.php";
NSURL *url = [[NSURL alloc] initWithString:path];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
id cachedJson = [[NSUserDefaults standardUserDefaults] valueForKey:path];
if (cachedJson) {
[self didUpdateJSON:cachedJson];
} else {
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[self didUpdateJSON:JSON];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSUserDefaults standardUserDefaults] setObject:JSON forKey:path];
[[NSUserDefaults standardUserDefaults] synchronize];
});
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
Fetch data from JSON parser and store it in an array. After that you can add it to a SQLite database.
You should create path in proper way
replace this
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
with
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"data.json"];
Anton , fetch the json data and store in the nsmutable array at the first time you Array hold the data when u run again ur array not a nil but replay the data to the second time ... and another way to store the data in local database...if u r needed to store the data..
but ur problem is solve for first one..ok best of luck..
Try using NSUserDefaults instead of writing this small JSON text to a file
- (void)writeJsonToFile
{
NSString *jsonString;
NSString *stringURL = #"http://volodko.info/ic/json.php";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData)
{
// JSON successfully downloaded, store it to user defaults
jsonString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
[[NSUserDefaults standardUserDefaults] setValue:jsonString forKey:#"jsonString"];
}
else
{
// no urlData, using stored JSON
jsonString = [[NSUserDefaults standardUserDefaults] valueForKey:#"jsonString"];
}
}
possibly even better:
- (NSString *)getJSON
{
<the code above>
return jsonString;
}
and then use it in other functions as:
NSString *jsonString = [self getJSON];
I have an iPad app which connects to a C# web service to download documents and images.
If I run it as a fresh install on the iPad, it downloads the expected documents and images. If I upload a new document and relaunch the app, it downloads it as expected. However, if I upload a new image to the server and run it again, it doesn't download the new image.
Here is the code for checking and downloading documents:
- (void)checkFiles:(NSString *)sessionID
{
fileList = [[NSMutableString alloc] init];
// get contents of doc directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:downloadsFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#", downloadsFolderString,file]
isDirectory: &isDirectory];
if ([file rangeOfString:#"LinkIcons"].location == NSNotFound)
{
if (!isDirectory)
{
[fileList appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
}
// create string to send to server
NSString *post = [NSString stringWithFormat:#"sessionID=%#&fileList=%#&dateTime=%#&userID=%#", sessionID, fileList, timeOpened, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
// get response - list of files for download
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (responseData)
{
NSString *requiredFilesList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// remove xml nodes from list
NSArray *lines = [requiredFilesList componentsSeparatedByString: #"\n"];
if (lines.count > 2)
{
// create sub array without xml nodes
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded = theRange.length;
if (numberOfFilesToBeDownloaded <= 0)
{
_jobStatusLabel.text = #"Documents up to date";
}
if (numberOfFilesToBeDownloaded > 0)
{
NSArray *subArray = [lines subarrayWithRange:theRange];
[self getFiles:subArray];
}
}
}
[self checkLinks];
}
and:
- (void)getFiles:(NSArray *)filenames
{
downloadManager = [[DownloadManager alloc] init];
downloadManager.delegate = self;
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:#"downloads"];
for (NSString *filename in filenames)
{
NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:filename];
NSString *baseUrlString = SERVER_DOWNLOAD_URL_STRING;
NSString *finalUrlString = [baseUrlString stringByAppendingPathComponent:[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[downloadManager addDownload:downloadFilename fromUrl:[NSURL URLWithString:finalUrlString] ];
[self notifyServerFileDownloaded:filename];
}
}
And this is the corresponding code for the images:
- (void) checkLinks
{
NSMutableString *linkListOnDevice = [[NSMutableString alloc] init];
NSMutableArray *globalLinksArray = [[[NSUserDefaults standardUserDefaults] objectForKey:#"globalLinksArray"]mutableCopy];
if(globalLinksArray != nil)
{
NSLog(#"Links Array found. Contents: %#", globalLinksArray);
}
else
{
globalLinksArray = [[NSMutableArray alloc] initWithCapacity:0];
}
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSString *LinksFolderString = [downloadsFolderString stringByAppendingPathComponent:#"/LinkIcons"];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:LinksFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#",downloadsFolderString,file]
isDirectory: &isDirectory];
if (!isDirectory)
{
[linkListOnDevice appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
// create string to send to server
NSString *post = [NSString stringWithFormat:#"iconsList=%#&userID=%#", linkListOnDevice, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_LINK_ICONS_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
// get response - list of files for download
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *requiredIconsList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// remove xml nodes from list
NSArray *lines = [requiredIconsList componentsSeparatedByString: #"\n"];
// create sub array without xml nodes
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded += theRange.length;
NSArray *linkSubArray = [lines subarrayWithRange:theRange];
NSMutableArray *iconsArray = [[NSMutableArray alloc] initWithCapacity:0];
NSString *linkDetail;
for (linkDetail in linkSubArray) {
[globalLinksArray addObject:linkDetail];
}
[[NSUserDefaults standardUserDefaults] setObject:globalLinksArray forKey:#"globalLinksArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
// separate file for download from rest of string
for (NSString *linkString in linkSubArray)
{
NSArray *spltArray = [linkString componentsSeparatedByString:#"^"];
NSString *linkIconString = spltArray[3];
[iconsArray addObject:linkIconString];
}
[self getLinks:iconsArray];
}
and:
- (void) getLinks: (NSMutableArray *) linkList
{
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:#"downloads"];
for (NSString *filename in linkList)
{
NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:filename];
NSString *baseUrlString = SERVER_DOWNLOAD_URL_STRING;
NSString *finalUrlString = [baseUrlString stringByAppendingPathComponent:[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[downloadManager addDownload:downloadFilename fromUrl:[NSURL URLWithString:finalUrlString] ];
}
}
Can anyone shed any light on why this works for documents but for images only on first run but not subsequently?
1) write this on didFinishLaunchingWithOptions method
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"FirstTime"];
if (![savedValue isEqualToString:#"1"])
{
//Call for download image OR image downloading coding.
}
2) When image downloading complete then store value in NSUserDefaults
NSString *valueToSave = #"1";
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"FirstTime"];
3) when next time your app is run then (1) condition is true and it not download image next time. If you want to download this then delete your app from simulator or device and clean then run the app.
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.