Whenever anyone worked on an app that deals with the photo library, they did a google search on how to add photos to the iOS simulator at least once!
The boring way! π
The most common approach would be to search for an image in safari. Then long-press the image and save to photos. Another approach would be to download the photo in your mac, drag it to the simulator. Then do the same thing as before! This is cumbersome and tiring at the same time. What if you need to download multiple images? Annoying steps, right?
The cooler way: xcrun simctl
to the rescue! π¦ΈββοΈπ¦ΈββοΈ
There is a much easier and cooler way to add photos in the iOS Simulator. That is by using the xcrun simctl
command.
To add a single photo to the currently running simulator, first, navigate to the destination directory. Then use the command below in terminal (replace the <image_name>
with the actual name of the image):
$ xcrun simctl addmedia booted ./<image_name>.jpg
Code language: HTML, XML (xml)
If you want to add this image to a specific simulator, you need to pass its device id. The device id of the available simulators can be found by running:
$ xcrun simctl list
Code language: PHP (php)
Next, you need to run the following command along with the simulator id as following:
$ xcrun simctl addmedia D0BD5CE0-FC24-4DD4-B688-2A882D4A69A7 ./image_name.jpg
Replace D0BD5CE0-FC24-4DD4-B688-2A882D4A69A7
with your desired simulator device id.
Save multiple photos: unleash the Bash! π
Let’s say you need 20 (n) images to be added to the simulator. Downloading and adding them 1 by 1 would be annoying and repetitive. The good news is, whenever you have a repetitive task, you can automate it! π
Let’s assume you have got n
images downloaded in a folder called SimulatorGallery
. Now, you need a way to iterate through these images to automate the above process. Thankfully, the bash script comes with a really cool tool called awk
, which makes it super easy. To use awk
you need to state a begin, end and the execution block as
$ awk 'BEGIN { <CONDITION> <STATEMENT> } { <EXECUTION_STATEMENT> } END { <STATEMENT }
Code language: HTML, XML (xml)
You can specify a command to find all .jpg
images in this folder and add them to your specified/booted simulator. Run the following command:
$ awk 'BEGIN{} { print "xcrun simctl addmedia booted ./"FILENAME; nextfile } END{} ' *.jpg | sh
Code language: JavaScript (javascript)
The pipe | sh
is specifying that the print
statement should actually be a shell command.
Finally
Now if you visit your simulators Photos
app, you’ll see all the photos there. It’s pretty damn cool, isn’t it? It doesn’t matter how many photos you want to add, you just need to specify the file format and visit that directory from the terminal.
Happy coding!