suMi
suMi

Reputation: 1546

simple way to save image for later sending to database?

Hei, I'm rather new to objective C and I don't call myself a programmer but a creative coder (someone who makes things work, I don't care so much about elegancy of my solutions ;) ). I have the following problem to solve: My app takes photos and stores them in the apps documents directory. It sends these images to a custom database. Working fine so far.

Some test-users have requested to capture their photos offline and whenever they open the app again and internet connection is available it would send the images to the database. Now I've found the quite easy way to test whether there is internet connection available here: How to check for an active Internet connection on iOS or OSX?

works fine so far. Next I'm wondering how I'd best save the images that need to be sent whenever no internet connection is available. I'm using NSUserDefaults in my app already. Would it be an easy solution to save the names/paths of the images that need to be sent using NSUserDefaults and read them when the app is opened and send all the images at that time?

or can someone recommend another easy way to do it? Suggestions welcome!

Upvotes: 0

Views: 106

Answers (4)

JWKot
JWKot

Reputation: 360

You can probably use NSUserDefaults. However, a very practical and simple approach I would take is this:

  • Create a directory in which you save the images, you can't upload right away
  • Upload these, when internet is available
  • When the upload is finished, just delete the pictures.
  • Everytime the app is launched/ internet connection changes check if there are images left in the directory

Upvotes: 0

wootage
wootage

Reputation: 936

NSUserDefaults could be the best way if you have 2-3-5 images to save, otherwise use coredata or create plist in your documents folder and when you have internet you can take all the paths from coredata or plist and upload the images

Upvotes: 1

Lucas Brito
Lucas Brito

Reputation: 1028

I think NSUserDefaults is the best way. You keep the observer for when the internet connection is available and then send. Here's is an example how to save an image in NSUserDefaults:

NSData *imageData = UIImageJPEGRepresentation(image, 1);

NSString *imagePath = [self documentsPathForFileName:[NSString stringWithFormat:@"image_%f.jpg", [NSDate timeIntervalSinceReferenceDate]]];

[imageData writeToFile:imagePath atomically:YES];

[[NSUserDefaults standardUserDefaults] setObject:imagePath forKey:kPLDefaultsAvatarUrl];
[[NSUserDefaults standardUserDefaults] synchronize];

Note: You shouldn't save image data directly into NSUserDefaults

Upvotes: 0

rustylepord
rustylepord

Reputation: 5801

You can save the offline images in the caches directory and upload them as batch ones the internet connection is available. Have a look a this post.

How can I get a writable path on the iPhone?

Upvotes: 0

Related Questions