Last active
February 18, 2021 19:44
-
-
Save manas-sharma-1683/a3a794522c0cd929a2e34a3f2d3e6fb1 to your computer and use it in GitHub Desktop.
How to access asset catalogs from your Xcode project.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# !/usr/bin/python3 | |
""" | |
Asset catalogs are not accessible in your Xcode project because they are compiled archive (.car files) so doing | |
something like Bundle.main.url().. won't work. | |
""" | |
""" | |
1. Manually add a file colors.json to your Xcode project on the level ${PROJECT_DIR}/project_name/<here> and | |
add it as a member of the target. | |
2. Add this script in ${PROJECT_DIR}/<here>. | |
3. Add a new Xcode Build Phase Run Script ( python3 ${PROJECT_DIR}/access_catalogs.py ). | |
4. This script collects colors name from ${PROJECT_DIR}/SomeAssetCatalog.xcassets and generates colors.json file ( or overwrite ) | |
which is already present in Xcode bundle and is a member of the target ( done in step 1 ). | |
""" | |
import os | |
import sys | |
import json | |
json_file = "colors.json" | |
color_set_extension = ".colorset" | |
color_path = "project_name/SomeAssetCatalog.xcassets" | |
def check_for_paths(): | |
if not os.path.exists(color_path): | |
print(f"{color_path} does not exist.", file= sys.stderr) | |
exit(1) | |
# ignore files like .DS_Store or Contents.json | |
def remove_extra_files(file_name: str) -> bool: | |
if color_set_extension in file_name: | |
return True | |
return False | |
# remove .colorset extension for all files | |
def remove_extension(file_name: str) -> str: | |
index = file_name.index(color_set_extension) | |
return file_name[: index] | |
def main(): | |
check_for_paths() | |
abs_path = os.path.abspath(".") | |
os.chdir(color_path) | |
all_files = os.listdir(".") | |
color_set_files = filter(remove_extra_files, all_files) | |
removed_extension_file_names = map(remove_extension, color_set_files) | |
final_files_list = list(removed_extension_file_names) | |
final_files_list.sort() | |
payload = { | |
"colors": final_files_list | |
} | |
os.chdir("../") | |
with open(json_file, mode= "w") as path: | |
json.dump(payload, path, indent= 4) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment