Storing Images Locally on an iOS Device

Storing images locally on an iOS device

The simplest way is to save it in the app's Documents directory and save the path with NSUserDefaults like so:

NSData *imageData = UIImagePNGRepresentation(newImage);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];

NSLog(@"pre writing to file");
if (![imageData writeToFile:imagePath atomically:NO])
{
NSLog(@"Failed to cache image data to disk");
}
else
{
NSLog(@"the cachedImagedPath is %@",imagePath);
}

Then save the imagePath in some dictionary in NSUserDefaults or however you'd like, and then to retrieve it just do:

 NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];

Storing images and files in iOS devices

You certainly can save to the local user directory for the app, though keep in mind that this is sandboxed by iOS so that each app has its own document directory.

For example, here is code (Swift 3) to get a "Database Working Folder":

// The working folder for our DB. This will be in the user's document store!
var _dbWorkingFolder: String?
// We're just going to use the user's document folder
_dbWorkingFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

It is possible to use AppGroups to have 2
or more apps that you control share a single space. But keep in mind this AppGroup has to be engineered into all apps that use it!

Here is Apple's doc on the iOS file system

Here is Apple's doc on writing App Extensions which actually uses AppGroups to allow an extension and and App to share space.

Finally, yes there is full support for you to write to the Photo Library. You'll want to use the Photos Framework and the images and videos are simply saved into the iOS "Photos" app. You can create a folder to hold your App's images, for instance.

Here is a link to Apple's Photos Framework.

If you have more specific questions, be sure to post those along with code you've tried and you'll get lots of help here!

How can I store images and strings locally on Swift

When storing this kind of data, you have 2 options (In fact you have more than 3 options, but saving image to the disk is IMHO complicated for this.) -

  1. UserDefaults
  2. Database like CoreData/Realm/FireBase...

The first one is recommended when there is not much data to save... For operating with more data, I would use database - CoreData...

For you operation you can use CoreData and NSFetchedResultsController (which is designed especially for fetching objects from the database)...

you can read the FetchedResultsController doc here... and core data basics here

Wish you best luck!

Storing photos on device: Local Database vs. Gallery

Definitely store the photos in a local file system or data storage solution. Otherwise, the photos will be shared/deleted without your knowledge or even the users knowledge of how they are important. This is also better because you wan't to give the user the ability to store them in their gallery only if they specify it.

With any app, you wan't ultimate control of what happens so that you can guide the user along a certain path. By storing the photos yourself, you get control of the data and can give control to the user as you see fit.

Never believe that the user is going to do what you expect. Or as my favorite saying goes, "always design for the dumbest user and you will have designed for all".

Correct way of storing large amount of images locally in the app

I would say the issue lies here:

destVC.image = ImageModel().instrumentImages[indexPath.row]

Every time you want to load a single image, you create an instance of ImageModel, which (I presume) loads all the images, and returns just one, the one you need. This is very inefficient, there's no point in loading all the images, get just one, and discard all the rest.

If you insist on pre-loading the images, load them just once and store them in a static instance of ImageModel, like so

class ImageModel
{
static let sharedInstance = ImageModel()

init()
{
// load images here
}
}

Then retrieve an image like so

destVC.image = ImageModel.sharedInstance.instrumentImages[indexPath.row]

This way you will load all images just once, in a constructor of the shared ImageModel instance.

However, I would argue that there's no point in loading all the images into memory - in your ImageModel class you should rather keep only file names of images, and load them only when necessary

class ImageModel 
{
let instrumentImages = ["accordion", "drums", ... ]

static let imageWithIndex(_ index : Int) -> UIImage?
{
return UIImage(named: instrumentImages[index])
}
}

and call it like so

destVC.image = ImageModel.imageWithIndex(indexPath.row)

No point in pre-loading images you might end up not even using, because with large quantity of high-definition images, your app might even run out of memory.

after picking the image how save images locally in ios

Yes, you can save the images in the document directory and keep the image file names in an array after that retrieve that images from doc. dir. just like this

// For error information
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/YOUR_IMG_FOLDER"];

if (![fileMgr fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

//Get the current date and time and set as image name
NSDate *now = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *gmtTime = [dateFormatter stringFromDate:now];
NSLog(@"The Current Time is :%@", gmtTime);

NSData *imageData = UIImageJPEGRepresentation(_postImage, 0.5); // _postImage is your image file and you can use JPEG representation or PNG as your wish
int imgSize = imageData.length;
////NSLog(@"SIZE OF IMAGE: %.2f Kb", (float)imgSize/1024);

NSString *imgfileName = [NSString stringWithFormat:@"%@%@", gmtTime, @".jpg"];
// File we want to create in the documents directory
NSString *imgfilePath= [dataPath stringByAppendingPathComponent:imgfileName];
// Write the file
[imageData writeToFile:imgfilePath atomically:YES];

**// Keep your Image file name into an mutable array here OR you can saved the array in a UserDefaults**

Then retrieve from doc. dir. from iterate the array.

//Get image file from sand box using file name and file path
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"YOUR_IMG_FOLDER"];
stringPath = [stringPath stringByAppendingPathComponent:imgFile]; // imgFile to get from your array, where you saved those image file names
UIImage *image = [UIImage imageWithContentsOfFile:stringPath];

Thank you...happy coding.

Xamarin.Forms: Thinking about ways to store images locally on the device user takes with camera

From my perspective, as I don't know PCLStorage that well, I would recommend that you can do one of the following.

  1. Take photo normally with MediaPlugin. When it is stored on the device you get back path to it. You can store that path it in your database.
  2. You can store blob of an image in the database.

If I were you I would simply create PoC with the first solution. Storing blobs in Db is time-consuming. With the first approach iOS/Android is taking care of the image being stored and you only take care of the link.

Save video to storage without having it show up in photos gallery (Swift iOS)

Saving a video onto the storage will not display in the Photo Gallery, in iOS/iPad OS the Photo Gallery requires another set of permissions and you have to specifically save in the Foto Gallery.

I would recommend to use your app isolated storage as the user can not see the files with 3rd apps or even Apple's File Manager.

For that take a look into FileManager class witch allows you to save files onto the disk.

I leave this tutorial as starting point iOS FileManager in Swift

how to save image and data locally in iphone device

HI,

Have u tried this method

UIImageWriteToSavedPhotosAlbum(image, self, (SEL)@selector(Imageview.image:didFinishSavingWithError:contextInfo:), nil); 


Related Topics



Leave a reply



Submit