Were you looking for the best games to play at daisyslots? Why not try starburst or fluffy favorite to experience something new? This will show you how to save and load images in a way that is very easy and straight forward.
Here is the function to save your image first.
We’ll assume you already have an UIImageView, containing an image, named ‘image’ :
1 2 3 4 5 6 7 8 9 |
func saveImage (image: UIImage, path: String ) -> Bool{ let pngImageData = UIImagePNGRepresentation(image) //let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG let result = pngImageData!.writeToFile(path, atomically: true) return result } |
Here is how to use the function later in your code:
1 |
saveImage(image, path: imagePath) |
However before you can Save or Load anything you have to know the ‘path’ you are going to use.
We’ll need 3 things:
-
-
- a function to pinpoint the documents directory
- a function to pinpoint a file in the documents directory
- a variable to store the location ( path ) of the image we want to save
-
Here is how we are going to do that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
func getDocumentsURL() -> NSURL { let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] return documentsURL } func fileInDocumentsDirectory(filename: String) -> String { let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename) return fileURL.path! } // Define the specific path, image name let imagePath = fileInDocumentsDirectory(myImageName) |
At this point you already have the image saved to the documents folder inside your app folder.
Keep in mind that folder will keep changing when using the IOS Simulator.
Here is how to declare the function for loading an image from a Path:
1 2 3 4 5 6 7 8 9 10 11 12 |
func loadImageFromPath(path: String) -> UIImage? { let image = UIImage(contentsOfFile: path) if image == nil { print("missing image at: \(path)") } print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder. return image } |
Now we can use that function and load our image and
apply it to an imageView you might have for an example:
1 2 |
image = loadImageFromPath(imagePath) imageView.image = image |
Here is how the full example should look:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import UIKit func getDocumentsURL() -> NSURL { let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] return documentsURL } func fileInDocumentsDirectory(filename: String) -> String { let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename) return fileURL.path! } class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Define the specific path, image name let myImageName = "image.png" let imagePath = fileInDocumentsDirectory(myImageName) if let image = imageView.image { saveImage(image, path: imagePath) } else { print("some error message") } if let loadedImage = loadImageFromPath(imagePath) { print(" Loaded Image: \(loadedImage)") } else { print("some error message 2") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func saveImage (image: UIImage, path: String ) -> Bool{ let pngImageData = UIImagePNGRepresentation(image) //let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG let result = pngImageData!.writeToFile(path, atomically: true) return result } func loadImageFromPath(path: String) -> UIImage? { let image = UIImage(contentsOfFile: path) if image == nil { print("missing image at: \(path)") } print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder. return image } } |
If you have any question or encounter any errors – please let me know. Cheers!
Hi, Thanks for the tutorial. Will this save to a directory on a real device when running the app?
Yes, this will save to the default documents folder on your iOS device. If you have a SDK license you can test it, for example with you iPhone plugged in to xCode.
Hey, when I try to return the image from the loadImage fund I get image == nil, directory is /Users/……../Library/Developer/CoreSimulator/Devices/5AB84EDB-424E-4667-8F81-1477FB84E542/data/Containers/Data/Application/928A445B-47E8-4957-AE13-AD913E3B2530/Documents/Case3a.png
The Application/928A445B-47E8-4957-AE13-AD913E3B2530/ is actually not there….is this expected? You mentioned the destination would change every run. I am saving the URL to core data and then reloading it when app runs again but then the URL does not exist
Yes, that’s how it is on the simulator. On a real device will stay the same. Return the image within the same run and you’ll see it ๐ So just make 2 UIImageView’s one that will pick up the image and save it and once it’s saved the second UIImageView will auto-load it ๐ This should work fine.
You don’t have an SDK to try it on a real device ?
Sure I’ll try on real device. So why is directory deleted on simulator but not real device? Awkward for testing
It doesn’t get deleted, it’s still there, however on every run the iOS SImulator creates a new folder with it’s unique run-code. Folders are still there, so you should be able to find them in Finder and go there if you copy/paste the location. I don’t think anybody likes this, but since xCode 6 it’s been like that :/
What you can try and do is this: run your app, don’t close the Simulator but press the HOME button, close the app , within the simulator, then reopen it. This should work .
tried on a real device same issue: returns nil when image = UIMage(contentsOfFile : path); is called, location on device is…No image loading form path : /var/mobile/Containers/Data/Application/F6A88C03-EBDF-48CB-B9AE-7EBCDC06036F/Documents/Case3a.png
Log
Image is stored in this location – can find in Finder: /var/mobile/Containers/Data/Application/F6A88C03-EBDF-48CB-B9AE-7EBCDC06036F/Documents/Case3a.png
Let me see your full code and I’ll try it. Upload on GitHub or something if you can.
Can i send u swift file? Am very new to github and having problems trying to upload
Yep. You have access to the Slack already right ? You can just post it there.
DO i direct message u on Slack?
You can just post it in the help section. This way someone can help out or benefit from the answer.
ok just added comment, could not see where to upload a file, and someone posted me a link back here…
That link popped up because you pasted a link. Let me know if you are still having problems with it.
The image is saved and returned only in same instance of app running, in between runs although same url a nil is returned….I am taken the saved url form core data and populating a collection view….
I haven’t had that happen on a real device. Send me at least the save/load/path functions.
Hey,
So found the issue , this may be useful for others trying to save and retrieve to/from core data with this code. You have to save the imageName (String) ONLY to core data. When saving to docs directory and retrieving form docs directory use documentsDirectory(imageName) – where imageNAme is retrieved/saved form/to core data object. Im guessing the abs path changes every run on simulator and device run form Xcode, so by calling documentsDirectory(imageName) it will find current docs dir on current run, anyway after many hours it works ๐ Thanks for all your help.
Oh, yeah, I forgot about the fact that you are using CoreData ๐ Generally try and save only the imageName as String – yes. Besides anything else, there is no need to save/load the directory path, since it’s always the same ๐ Thanks for letting me know. Good job !
Also make sure you install GitHub app on your Mac so you can upload your projects there. That’s the easiest way to get help later one, especially once your project files become very long.
Really useful stuff – thanks!
Glad you liked it ๐
Thank you you made it look simple and it worked for my app perfectly
Glad that helped you ๐
Glad that helped you ๐
Thank you you made it look simple and it worked for my app perfectly
How do I acknowledge your code that I have used
What do you mean ?
Just would like to acknowledge were bits of the code ideas came from in my code
Don’t worry mate, just glad to help. If you need to just keep notes for yourself you can just comment/pseudo-code ๐
You can just put comments in your code / pseudo code.
What do you mean ?
How do I acknowledge your code that I have used