Save images from URL to iOS Directory - ios

I want to save a lot (800-2000) images from server to iPhone app directory (Documents directory).
First of all I have to check if those image are already on the iPhone directory.
I use this code to download one image:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"pkm.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[thedata writeToFile:localFilePath atomically:YES];
Please help me, any suggestions:
1. Save all images with the original name on iPhone directory, NOT "pkm.jpg"
2. Save images with names: from 05052008321_bigger to 05052008350_bigger
3. Check if images are downloaded already, DON'T Download again.
I know, maybe this is more than a question. But some suggestions, directions will be really good.
Thanks in advance.

A couple of reactions:
You're initiating a NSURLConnection connectionWithRequest (which triggers the NSURLConnectionDataDelegate methods), but you then apparently disregard that and initiate a dataWithContentsOfURL. You should pick one or the other, but don't do both.
I'd suggest you pursue a NSOperation-based solution because you'll definitely want to (a) enjoy concurrency; but (b) limit the concurrent operations to some reasonable number (say 4 or 5), otherwise you'll have requests timing out and failing.
In terms of getting the filename, you can retrieve the filename using lastPathComponent from the NSURL. (My download operation, used below, actually will automatically use this if you don't provide an explicit filename.)
You haven't illustrated how you're determining the list of filenames from the remote server, so we'd have to see how you know what images there are to retrieve.
If this is for your own purposes, this is fine, but I've heard claims that Apple rejects apps that request too much data over a cellular connection (and 2000 images would certainly qualify). Frankly, even if Apple doesn't raise a fuss, you really should be asking the user before using that much of their data plan. You can use Reachability to determine whether the user is connecting via wifi or via cellular, and if the latter, you may want to present a warning.
But I'd suggest something that looks like (assuming you have some NSArray with NSString versions of the URL's ... obviously adjust this for whatever form your list of URLs is in):
NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];
downloadQueue.maxConcurrentOperationCount = 4;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
for (NSString *urlString in urlStrings)
{
NSURL *url = [NSURL URLWithString:urlString];
NSString *path = [docsPath stringByAppendingPathComponent:[url lastPathComponent]];
if (![fileManager fileExistsAtPath:path]) {
DownloadOperation *downloadOperation = [[DownloadOperation alloc] initWithURL:url];
downloadOperation.downloadCompletionBlock = ^(DownloadOperation *operation, BOOL success, NSError *error) {
if (error) NSLog(#"download of %# failed: %#", operation.url, error);
};
[downloadQueue addOperation:downloadOperation];
}
}
And that download operation might be something like this. Obviously, use whatever NSOperation based downloader you want, but I'd suggest you use one that doesn't load the whole download into memory, but rather one that streams it directly to persistent storage.
If you don't want to get that fancy, you could just do something like:
NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];
downloadQueue.maxConcurrentOperationCount = 4;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
for (NSString *urlString in urlStrings)
{
NSURL *url = [NSURL URLWithString:urlString];
NSString *path = [docsPath stringByAppendingPathComponent:[url lastPathComponent]];
if (![fileManager fileExistsAtPath:path]) {
[downloadQueue addOperationWithBlock:^{
NSString *path = [docsPath stringByAppendingPathComponent:[url lastPathComponent]];
NSData *data = [NSData dataWithContentsOfURL:url];
if (data)
[data writeToFile:path atomically:YES];
}];
}
}
Clearly, use whatever download operation class you want for downloading, but hopefully you get the basic idea. Create a NSOperation-based download, and then submit one for every file that needs to get downloaded.

I'm not sure the best method to serialize the information (naively, you could just write the NSDictionary to the disk). I would have a large NSDictionary (which could be broken up into smaller ones, up to you how to do that). The NSDictionary would take the image name "05052008321_bigger" and map it to a simple #YES.
When the app is in a position to download a new image, it would read the NSDictionary from disk (can be read in a different thread), and check if the image name is in the dictionary. This allows lookups to be fast.
- (BOOL)checkIfImageHasBeenDownloaded:(NSString *)imageName
{
return [self.dictionaryNames objectForKey:imageName] != nil;
}

Related

Objective-C create mapped file for PDF

I am creating a file like so:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,PDFFile];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:dataBytes attributes:nil];
}
_previewItemURL = [NSURL fileURLWithPath:filePath];
and I am displaying it in an UIDocumentInteractionController like so:
if (_previewItemURL) {
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:_previewItemURL];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
}
However, sometimes the PDF file I am saving off bytes are way too big, sometimes 5.5MB, which causes UIDocumentInteractionController to some time to load the PDF. I was doing some reading here https://stackoverflow.com/a/27863508/979331 and it is suggested to create a 'mapped' file. My question is I don't understand how to create one. I have been googling like crazy for the past two days and I just don't understand it.
I think the issue is with the PDF because I tried this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pgnPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.pdf", #"example"]];
//filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,PDFFile];
//if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSString *newFile = [[NSBundle mainBundle] pathForResource:#"example" ofType:#"pdf"];
[[NSFileManager defaultManager] copyItemAtPath:newFile toPath:pgnPath error:&error];
//[[NSFileManager defaultManager] createFileAtPath:filePath contents:dataBytes attributes:nil];
//}
//_previewItemURL = [[NSBundle mainBundle] URLForResource:#"example" withExtension:#"pdf"];
_previewItemURL = [NSURL fileURLWithPath:pgnPath];
with a PDF that was 5.5MB and everything seemed fine, could the issue be with how I getting the PDF? I am getting the bytes from a web service, here is my call:
task = [dataSource.areaData GetPDFFileTestTwo:[NSString stringWithFormat:#"%#",encodedUrlStr] completion:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
NSData *dataBytes;
for (NSDictionary *dict in tableArray) {
NSString *base64 = dict[#"data"];
dataBytes = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
}
if (dataBytes) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,PDFFile];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:dataBytes attributes:nil];
}
_previewItemURL = [NSURL fileURLWithPath:filePath];
if (_previewItemURL) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:_previewItemURL];
documentInteractionController.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
[documentInteractionController presentPreviewAnimated:YES];
});
});
}
}
}];
And here is GetPDFFileTestTwo
-(NSURLSessionDataTask *)GetPDFFileTestTwo:(NSString *)PDFFile completion:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler{
NSString *FileBrowserRequestString = [NSString stringWithFormat:#"%#?PDFFile=%#",kIP,PDFFile];
NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if(completionHandler)
{
completionHandler(data, response, error);
}
}];
[dataTask resume];
return dataTask;
}
kIP is a string and that is the web service URL
You're not "creating" a mapped file. You're reading it into NSData as mapped to the bytes in the file. That means, that in-memory NSData bytes are underneath mapped to bytes in the file.
Here is a way to read a file as mapped:
https://github.com/atomicbird/atomictools/blob/master/NSData%2BreallyMapped.h
If you can't pass NSData to the controller for preview, mapping makes no sense. Even if you can, you have to be sure that controller won't copy your data before it is used.
Consider using PDFKit framework, where you can initialize PDFDocument with NSData and display it in PDFView.
Your questions;
create a 'mapped' file. My question is I don't understand how to
create one.
So let me point out that UIDocumentInteractionController has no inputs that accept NSData, so you wouldn't be able to create a memory mapped file to use with it. I also examined the header for any other clues, and didn't find any.
https://developer.apple.com/documentation/uikit/uidocumentinteractioncontroller
In looking for a solution, I saw that QLPreviewController mentions 'data' but I find it didn't accept NSData either.
https://developer.apple.com/documentation/quicklook/qlpreviewcontroller
I finally settled on WKWebView in WebKit, which does support using NSData, that is Memory Mapped, and loads quite quickly with a 15 MB PDF full of pictures and text I made.
I created a project with the large PDF and tried it out, it works fine. Please feel free to examine it.
https://github.com/eSpecialized/PDFDocViewerMapped
How 'mapped' works;
Anything that can take NSData can use a mapped file unless it needs the entire set of data at once. A PDF with a single image vs a multipage PDF are good examples of what can't be mapped and what can be mapped.
NSError *errors;
NSData *docFileData = [NSData dataWithContentsOfFile:docFileWithPath options:NSDataReadingMappedAlways error:&errors];
Options for NSData mapped;
https://developer.apple.com/documentation/foundation/nsdatareadingoptions?language=objc
NSDataReadingMappedIfSafe // Hint to map the file in if possible and safe
NSDataReadingMappedAlways // Hint to map the file in if possible. This takes precedence over NSDataReadingMappedIfSafe if both are given.
could the issue be with how I getting the PDF?
Fetching a PDF remotely means you must download the document.
Think of what you are doing, fetching the Pdf, saving it locally, then opening it in the UIDocument Interaction controller which takes URL's and not NSData.
I hope this meets your criteria for a solution;
UIDocumentInteractionController limitations with requiring URL's
WKWebView - allows using NSData that can be memory mapped.
3rd party options for PDF viewing - anything that can accept NSData is a
candidate for use. Look for CocoaPods and on GitHub for PDF, iOS PDF,
etc.

How to store .flac file content in NSData?

In my app I have added one .flac file in my resources folder. I want to send to this .flac file to Google's speech recognition service... Below is my code:
NSURL* urlGoogle = [NSURL URLWithString:#"https://www.google.com/speech-api/v1/recognize"];
NSMutableURLRequest *urlGoogleRequest = [[NSMutableURLRequest alloc]initWithURL:urlGoogle];
[urlGoogleRequest setHTTPMethod:#"POST"];
[urlGoogleRequest addValue:#"audio/x-flac; rate=16000" forHTTPHeaderField:#"Content-Type"];
NSURLResponse* response = nil;
NSError* error = nil;
NSArray *docDirs = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [docDirs objectAtIndex:0];
NSString *path = [[docDir stringByAppendingPathComponent:#"surround88"]
stringByAppendingPathExtension:#"flac" ];
NSURL* url = [NSURL fileURLWithPath:path];
//Here I'm getting flacData value is nil
NSData *flacData = [NSData dataWithContentsOfURL:url]; //flacData = nil
[urlGoogleRequest setHTTPBody:flacData];
NSData* googleResponse = [NSURLConnection sendSynchronousRequest:urlGoogleRequest
returningResponse:&response
error:&error];
id jsonObject=[NSJSONSerialization JSONObjectWithData:googleResponse options:kNilOptions error:nil];
NSLog(#"Googles response is: %#",jsonObject);
Since I'm not sending any data to the server, I'm getting empty response.
I have tested other 3rd party apis like openears, dragon, ispeech etc and not satisfied.
Can some one help me how to proceed to further. Is this the correct way to implement google's speech recognition functionality? Any help would be appreciated.
Since you're placing the file in your resources folder, you're not going to find it with NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);. That's why [NSData dataWithContentsOfURL:url] is returning nil.
Your file is now placed in your Bundle, so try loading the file's contents with this:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"surround88" withExtension:#"flac"];
NSData *flacData = [NSData dataWithContentsOfURL:url];
EDIT: based on comments bellow
Make sure the file is a member of the target you're building. In other words:
Select your .flac file
Make sure to check the boxes for the targets you're testing this with
Using the test project above, I was able to successfully create an NSData object from the .flac file.

How to store a UIImage locally to avoid an unnecessary server request?

I'm downloading an image and then displaying it with UIImageView. Using this approach the image is downloaded every time the view is loaded. How would I go about storing it locally to avoid an unnecessary server request?
[self requestData ] ;
UIImage *userImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:userProfileImageUrl ]]] ;
[self.profileImageView setImage:userImage ] ;
I would suggest using a library like SDWebImage that handles caching and asynchronous download.
Very first time, you have to save the image into NSDocumentsDirectory. For that you have to take the path of directory and append imageName like this
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString * documentsPathAppend = [documentsPath stringByAppendingFormat:#"/%#",[userProfileImageUrl lastPathComponent]];
And you have to write image with folowing condition
if(![[NSFileManager defaultManager]fileExistsAtPath:documentsPathAppend])
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:userProfileImageUrl]]];
[data writeToFile:documentsPathAppend atomically:YES];
}
After that you have to add this path into your local storage like core data. From next time you have to check whether image is there or not for particular URL in your core data.If it is there, then fetch the path from your core data and show like this
[self.profileImageView setImage:[UIImage imageWithContentsOfFile:imageEntity.imagePath]];
try this method to store UIImage in Local Directory..
- (void)addImage:(UIImage *)image toCacheWithIdentifier:(NSString *)identifier {
NSString *folderPath = #"LOCAL DIRECTORY PATH ";
if(![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:nil])
{
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *fileName = [NSString stringWithFormat:#"%#.png",identifier];
fileName = [folderPath stringByAppendingPathComponent:fileName];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:fileName atomically:YES];
}
to retrieve image from Local Directory try this method...
- (UIImage *)imageFromCacheWithIdentifier:(NSString *)identifier
{
NSString *folderPath = #"LOCAL DIRECTORY PATH ";
NSString *fileName = [NSString stringWithFormat:#"%#.png",identifier];
fileName = [folderPath stringByAppendingPathComponent:fileName];
if([UIImage imageWithContentsOfFile:fileName])
{
return [UIImage imageWithContentsOfFile:fileName];
}
return nil;
}
One other viable approach is to utilize NSURLCache (see also: Understanding Cache Access) in the official documentation.
The HTTP Cache was invented exactly for this requirement: Caching in HTTP in RFC 2616.
Unfortunately, HTTP Caching is an advanced topic, and the exact behavior of NSURLCache is quite obscure.

Objective C: Keep Image After App Termination

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];

Download an image from URL and store in device (can be Photos folder in iPod), NOT IN APPLICATION

I have an issue about downloading image from URL. After checking, I realized that I could download and stored image into application (connect iPod to MAC and open this application, I can find this image which has just downloaded from server), but this image hasn't appeared in Photos folder of device (my iPod). Following is my code:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"pkm.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]];
[thedata writeToFile:localFilePath atomically:YES];
Main task of my application is to download an image from server (via URL) and store image into Photo folder (or other folder that I can create), after that I use this image to set background for iPod.
Has anyone ever seen this case ? Please give me any ideas to resolve this issue.
Thanks anyway,
Ryan.
You will need to save the image to the photo album, you can use the ALAssetsLibrary classes for this. They might be a bit more steep to learn but very powerful.
Or use the very easy: UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo); method. This will just save the image to the Photo library.

Resources