Objective C: Keep Image After App Termination - ios

I am making an app that downloads files from an online server by clicking an Icon representing the file to be downloaded, then the file will be saved to the app's sandbox.
I have managed to do those mentioned above. Now, what I want to do is to put a "Check" image on the icon to allude the user that it is already downloaded.
I already tried it by putting another UIImageViewon top of the icon when the download is successful but when I fully terminate the app and re-open it, the image is gone and I need to download it again to show it.
How will I able to that?

Just keep an array of all the downloaded files, and at startup check to see which files to apply the check mark to.
For example:
When you get the image:
NSMutableArray *array;
array = [[NSUserDefaults standardUserDefaults] objectForKey:#"downloaded"].mutableCopy;
if (!array) array = [[NSMutableArray alloc] init];
[array addObject:somethingToIdentifyTheImageBy]; //For example, a string with the name of the image
[[NSUserDefaults standardUserDefaults] setObject:array forKey:#"downloaded"]
On startup:
NSArray *downloadedImages = [[NSUserDefaults standardUserDefaults] objectForKey:#"downloaded"];
forin (NSString *string in downloadedImages)
{
//Apply check mark
}

Use following code to Save your Downloaded Image to Library Directory of Device and Retrive it, as NSUserDefaults will not allow you to store Large amount of Data.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = paths[0];
NSString *imageFilePath = [libraryDirectory stringByAppendingPathComponent:#"myImageIcon.jpg"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:imageFilePath]) {
// File Exist at Library Directory, Just Read it.
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];
}
else
{
// File Doesn't Exist at Library Directory, Download it From Server
NSURL *url = [NSURL URLWithString:#"YOUR Image File URL"];
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSString *imagePath = [libraryDirectory stringByAppendingPathComponent:[url lastPathComponent]];
NSLog(#"Image Stored At %#",imagePath);
[imageData writeToFile:imagePath atomically:YES];
}

You cannot save anything inside the app's bundle, but you can store the image in your app's documents directory by using [NSData dataWithContentsOfURL:] method. This is not exactly permanent, but it stays there at least until the user deletes the app.
NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

Related

how to download jpg,png,pdf,doc.ppt,rtf,etc file from the google drive in objective c

I am new iPhone developer.I am developing iPhone app in this app Google drive integration it is successfully.but I want to download jpg,png,pdf,doc.ppt,rtf,etc file are download.
all file and folder display in Table view.I want do download the selected file from the table view.so how can do this ?
I am read this link https://developers.google.com/drive/v2/reference/files/get but i can not understand.here how to call all this function.
I want to download file's from Google Drive and save in document directory.
I am try this code.
NSString *downloadedString = file.downloadUrl; // file is GTLDriveFile
NSLog(#"%#",file.downloadUrl);
GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadedString];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
{
if (error == nil)
{
if(data != nil)
{
GTLDriveFile *file = [driveFiles objectAtIndex:indexPath.row];
NSString *filename=file.title;
//this variable globalObj.documentPath is global variable for document directory path.
filename = [globalObj.documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",filename]];
filename=[filename stringByReplacingOccurrencesOfString:#"file:/private" withString:#"file:///"];
NSLog(#"File name : %#",filename);
NSURL *targetURL=[[NSURL alloc] initFileURLWithPath:downloadedString];
NSData* Data = [[NSData alloc]initWithContentsOfURL:targetURL];
[Data writeToFile:filename atomically:YES];
NSLog(#"my path:%#",filename);
}
}
else
{
NSLog(#"Error - %#", error.description);
}
}];
so places help me.I want to download file and save in document directory.
any link for code places suggestion me.
Thanks
you does not have to do all this stuff.
here is just simple code
image url is from dropbox.
NSString *stringURL = #"https://dl.dropboxusercontent.com/s/pquhnr5pt37uk6q/backkk.jpeg?dl=1&token_hash=AAEXBejAXoD__RPMBom6nL2F5_Uhu62ed0puhtLIt2FGug";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"yourfile.png"];
[urlData writeToFile:filePath atomically:YES];
}
and finally you can represent it any way you want.
If you want to download large data.then use Threading concept.
if you use imageview programetically then write below code..... myimg=[[UIImageView alloc]initWithFrame:CGRectMake(30, 100, 100, 100)];
myimg.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/pquhnr5pt37uk6q/backkk.jpeg?dl=1&token_hash=AAEXBejAXoD__RPMBom6nL2F5_Uhu62ed0puhtLIt2FGug"]]];
[self.view
addSubview:myimg]; it's working

Can I async UIImageJPEGRepresentation writeToFile?

I am doing the following when I get an image back from the server. But this code is bringing my app to its knees. It freezes up the UI.
Can this be run on a background thread in iOS? Can I use async?
if (![NSString isEmpty:user.avatarURL])
{
NSString *pathToImage = user.avatarURL;
NSURL *url = [NSURL URLWithString:pathToImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
[[NSUserDefaults standardUserDefaults] setObject:UIImageJPEGRepresentation(image, 1) forKey:kUserImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"userAvatar.png" ];
NSData* jpegdata = UIImageJPEGRepresentation(image, 1);
[jpegdata writeToFile:path atomically:YES];
}
As #valentin says, you can do everything inside the if() statement in a dispatch_async() call.
Note I suspect what’s probably slowing you down is actually the -dataWithContentsOfURL:, not the UIImageJPEGRepresentation(), so you’ll want to make sure that’s inside your dispatch_async, not outside.
Also, I’m not clear why you’re decompressing the data into an image, then re-compressing it. You’re going to get artifacts doing this, and with most services the avatar image is going to be compressed anyhow.
I’d do the following:
if (user.avatarURL)
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *const imageURL = [NSURL URLWithString:user.avatarURL];
if (!imageURL)
return;
NSData *const imageDdata = [NSData dataWithContentsOfURL:imageURL];
if (!imageDdata.length)
return;
[[NSUserDefaults standardUserDefaults] setObject:imageDdata forKey:kUserImage];
[imageDdata writeToFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:#"userAvatar.png"] atomically:YES];
});
The line which is doing most damage is:
NSData *data = [NSData dataWithContentsOfURL:url];
Because it does the download from the network. Nothing in your code updates the UI so it can all be run on a background thread. Just ensure that if you post a notification or subsequently update the UI after the image is saved that you switch back to the main thread.

how to download files from url and store in document folder [duplicate]

This question already has answers here:
iOS download and save image inside app
(11 answers)
Closed 9 years ago.
I created one application that has two page (first page for show list of data and second page for show detail data).
when click on any cell go to next page and in next page exists one button with name : DOWNLOAD
that I want when I click on that button this file download and save in document folder.
I dont know about it. please guide me that how download any file and store in document folder.
I searching in internet but I dont understand about it.
please tell me with code that how downloaded any file with one button. Im sorry if I not good english.
It is this simple my friend,
NSString *stringURL = #"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
it advisable to execute the code in a separate thread.
EDIT 1: more info
1) for large file downloads,
-(IBAction) downloadButtonPressed:(id)sender;{
//download the file in a seperate thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSString *urlToDownload = #"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.png"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
});
}
});
}

How to save multiple xml files in cache file path in ios?

Im saving xml file in cache file path as follows:
// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
filePathl = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0],#"list.xml"];
// Download and write to file
NSURL *url = [NSURL URLWithString:detail_product_listing_rss];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePathl atomically:YES];
But using this code i can retrive data of recently used xml file.Could anybody please tell me how to save multiple xml files for offline use?
You need to save the xml with different names. Else it'll overwrite old xml.
Keep a integer value for this purpose, if you want this after the app restart also keep it in NSUserDefaults.
int posValue = [[[NSUserDefaults standardUserDefaults] objectForKey:#"lastXml"] intValue];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
filePathl = [NSString stringWithFormat:#"%#/list_%d.xml", [paths objectAtIndex:0],posValue];
NSURL *url = [NSURL URLWithString:detail_product_listing_rss];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePathl atomically:YES];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:posValue+1] forKey:#"lastXml"];

My images have been deleted after an app update

I'm trying to update my iPad app using TestFlight and the problem I have is that the images which I'm storing are being deleted when I update the app.
I'm using this code to downloading and later store the images:
NSData *responseData = [request responseData];
UIImage *imageURL = [[UIImage alloc] initWithData:responseData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(imageURL)];
[data1 writeToFile:documentsDirectory atomically:YES];
[imageURL release];
You are saving your image directly over (not inside) Documents directory. It should not even save the images in the first place. Instead create a subpath under Documents directory and save your file there.
NSString* imagePath = [documentsDirectory stringByAppendingPathComponent:#"someImage.png"];
[data1 writeToFile:imagePath atomically:YES];
The link which at the end solves my trouble was:
Problem with NSSearchPathForDirectoriesInDomains And Persistent Data
Thanks anyway!!

Resources