MarkHim
MarkHim

Reputation: 5776

Adding image to assets via script

I would like to add a bulk of images the .xcassets of iOS project via an external script at compile time (or manually at some other time but NOT ON RUNTIME - just to prevent misunderstanding)

So far I have been doing that via dragging and dropping the images to the assets in XCode, since then also the folder structure, contents.json and .pbproject file is updated

Is there a way to do that programmatically?

Upvotes: 5

Views: 710

Answers (1)

tunaahi333
tunaahi333

Reputation: 138

Here is a rough take on this which appears to work for me and it does not appear to require updates to the project file. It creates folders/and copies images into the folders within an existing xcassets container. It will copy a blank Contents.json template to each folder and add the image as a 3x image. I'm sure there are better ways of doing this as I rarely write shell scripts:

# Loop images in current directory
for filename in *.{jpg,gif,jpeg,png}; do
    # Prevent non-match GLOB from showing up 
    [ -e "$filename" ] || continue

    # Create imageSet folder
    IMAGESET_FOLDER=$PWD/../myapp/myassets.xcassets/${filename%.*}.imageset
    echo $IMAGESET_FOLDER
    mkdir $IMAGESET_FOLDER

    # Move image into folder
    cp $filename $IMAGESET_FOLDER/$filename

    # Create Contents.json for folder
    cp Contents.json $IMAGESET_FOLDER/Contents.json

    # Write image to contents.Json placeholder
    sed -i -e 's/\"3x"/"3x",\n"filename" : "'$filename'"/' $IMAGESET_FOLDER/Contents.json
done

The Contents.json file is just a blank file ready to have filenames appended:

{
    "images" : [
      {
        "idiom" : "universal",
        "scale" : "1x"
      },
      {
        "idiom" : "universal",
        "scale" : "2x"
      },
      {
        "idiom" : "universal",
        "scale" : "3x"
      }
    ],
    "info" : {
      "author" : "xcode",
      "version" : 1
    }
  }
  

Upvotes: 2

Related Questions