How to use custom Xcode Cloud environment variables? - swift

We have these environment variables within the Xcode Scheme
Which works well locally with this code
let webHost = ProcessInfo.processInfo.environment["HOST_URL"]!
let apiHost = ProcessInfo.processInfo.environment["API_URL"]!
let beamsKey = ProcessInfo.processInfo.environment["BEAMS_KEY"]!
let mixpanelKey = ProcessInfo.processInfo.environment["MIXPANEL_KEY"]!
However, when deploying using Xcode Cloud with the same environment variables.
It succeeds in building, but the app crashes with this log.
What is the right way to read these environment variables when using Xcode Cloud?

I had a similar issue, mostly i wanted to add an api-key in the project without this exist in the source code. So I had to create a ci_pre_xcodebuild.sh file
#!/bin/sh
echo "Stage: PRE-Xcode Build is activated .... "
# for future reference
# https://developer.apple.com/documentation/xcode/environment-variable-reference
cd ../ProjectName/
plutil -replace API_KEY_DEBUG -string $API_KEY_DEBUG Info.plist
plutil -replace API_KEY_RELEASE -string $API_KEY_RELEASE Info.plist
plutil -p Info.plist
echo "Stage: PRE-Xcode Build is DONE .... "
exit 0
and in the code we have
let key = config.preferences.debug ? "API_KEY_DEBUG" : "API_KEY_RELEASE"
guard let apiKey = Bundle.main.infoDictionary?[key] as? String

These variables are available and valid while the temporary environment is active to build the app only, not when the app is running on the device.
The environment variables can, however, be “captured” during the build process using shell scripts (see the Xcode "Build Phases" under the target settings or the Xcode Cloud custom build scripts).
Another good solution is to use some code generation tool like Arkana. This tool creates obfuscated code to make the variables available at the runtime eventually.
Again the tool or shell script must run in the Xcode Cloud environment. The steps to do this are out of the scope of this response.

So, this was an absolute headache but I finally figured out a satisfactory way to access and use these variables in code.
My solution uses:
A (gitignored) JSON file to store the variables locally
Xcode Cloud to send the variables in the CI
A ci_pre_xcodebuild.sh file to write the environment variables in the JSON
A Swift file that allows you to conveniently access the secrets.
Step 1: Basic JSON file
In your .gitignore file, add a new entry for the JSON file and its path
Create a JSON file through Xcode
Add your keys to this JSON file.
Secrets.json
(at: YourProject/SupportingFiles/secrets.json)
{
"STRIPE_KEY": "",
"GOOGLE_MAPS_KEY": "",
"GOOGLE_PLACES_KEY": "",
"BASE_URL": "https://dev.api.example.fr"
}
Step 2: Write the variables in Xcode Cloud
In this screenshot you can see that I've duplicated the keys for different environments. I didn't expand on this for the sake of brevity, but you can definitely have different secrets JSON files for different Xcode Scheme configurations.
Step 3: Add a ci_pre_xcodebuild.sh file
Important: the name of the files and their position matter.
The goal here is to add a script that the CI (Xcode Cloud) will execute each time it builds. In this script, we're going to create and fill our JSON.
Add a new group at the root of your project named "ci_scripts"
In this group, add a new file called ci_pre_xcodebuild.sh
Write the following:
#!/bin/sh
echo "Stage: PRE-Xcode Build is activated .... "
# Move to the place where the scripts are located.
# This is important because the position of the subsequently mentioned files depend of this origin.
cd $CI_WORKSPACE/ci_scripts || exit 1
# Write a JSON File containing all the environment variables and secrets.
printf "{\"STRIPE_KEY\":\"%s\",\"GOOGLE_MAPS_KEY\":\"%s\",\"GOOGLE_PLACES_KEY\":\"%s\",\"BASE_URL\":\"%s\"}" "$STRIPE_KEY" "$GOOGLE_MAPS_KEY" "$GOOGLE_PLACES_KEY" "$BASE_URL" >> ../Dream\ Energy/SupportingFiles/Secrets.json
echo "Wrote Secrets.json file."
echo "Stage: PRE-Xcode Build is DONE .... "
exit 0
Of course, you need to change this text depending on your keys and the location of the file. I added a few keys as an example.
In your Terminal, navigate to the new file's folder and run this command: chmod +x ci_pre_xcodebuild.sh. This fixes a warning in Xcode Cloud.
Step 4: [BONUS] A simple Swift file to access the environment variables
import Foundation
struct Secrets {
private static func secrets() -> [String: Any] {
let fileName = "Secrets"
let path = Bundle.main.path(forResource: fileName, ofType: "json")!
let data = try! Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
return try! JSONSerialization.jsonObject(with: data) as! [String: Any]
}
static var baseURL: String {
return secrets()["BASE_URL"] as! String
}
static var stripeKey: String {
return secrets()["STRIPE_KEY"] as! String
}
}

Related

How to get the current directory in iCloud Drive of macOS with Swift script?

I write Swift scripts to solve small tasks in using macOS.
I now need to get the current directory in my script.
The following program takes the path of the current directory as a string and converts it to an URL.
// myscript.swift
import Foundation
let path = FileManager.default.currentDirectoryPath
let url = URL(string: path)
print("path:", path)
print("url :", url)
When I ran it in ~/Downloads, I was able to get the URL of the current directory correctly.
The same was true for the other directories.
$ cd ~/Downloads
$ swift myscript.swift
path: /Users/myname/Downloads
url : Optional(/Users/myname/Downloads)
However, when I ran this program in iCloud Drive directory, I could not get the URL.
$ cd ~/Library/Mobile\ Documents/com\~apple\~CloudDocs/MyScripts
$ swift myscript.swift
path: /Users/myname/Library/Mobile Documents/com~apple~CloudDocs/MyScripts
url : nil
Is there any way to solve this?
I would like to solve this in order to handle files in iCloud Drive with my Swift scripts.
Thanks.
(I used a translation tool to ask this question.)
You need to encode the string since it contains a space
path = "/Users/myname/Library/Mobile Documents/com~apple~CloudDocs/MyScripts"
if let encoded = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: encoded) {
print(url)
}
/Users/myname/Library/Mobile%20Documents/com~apple~CloudDocs/MyScripts"

Trouble reading file in xcode command line app

I am having trouble reading a file within a command line tool project in Xcode 11.6.
Steps:
Create a new command line tool project using the template in the mac os section.
In main.swift:
import Foundation
let fileURL = URL( fileURLWithPath: "/Users/ausom4/Desktop/myTest.txt" )
var rawDataString: String
var errorString: String?
do {
rawDataString = try String( contentsOf: fileURL, encoding: .utf8 )
print(rawDataString)
} catch let error as NSError {
errorString = error.description
rawDataString = ""
print(rawDataString)
}
This will build successfully in Xcode however will always print a null string in the console.
However if I go to the location of my product in terminal and run the build I get the contents of the file.
I do not have sandboxing enabled. Sandboxing is also not enabled by default in this xcode template. I have also given xcode full disk access.
I can run this code in a playground.
What could be the issue here?
It is not sandbox - it is macOS Security & Privacy system.
On first launch you had to get alert asking something like “TestFileReading” would like to access files in your Desktop folder. so you grand access for this application.
If you did not grant access then (or for some reason macOS forgot to ask that) there is possibility to grant access manually in System Preferences at any time:
With all this passed your code snippet works as expected - tested with Xcode 12 / macOS 10.15.6

Getting errors when executing AppleScript from within Swift App [duplicate]

I try to run AppleScript command from Swift code like this:
var appleScriptCmd = "tell application \"System Events\" to make login item at end with properties {path:\"" + appPath + "\", hidden:false, name:\"Some App\"}";
var appleScriptCmd2 = "tell application \"System Events\" to set visible of process \"Safari\" to false";
and then I have tried both:
let script = NSAppleScript(source: appleScriptCmd2)!;
var errorDict : NSDictionary?
script.executeAndReturnError(&errorDict)
if errorDict != nil { print(errorDict!) }
or older approach:
Process.launchedProcess(launchPath: "/usr/bin/osascript", arguments: ["-e", appleScriptCmd])
neither works and simultaneously both commands I have tried are working from Terminal program using osascript -e "some command" tool.
Since your app is sandboxed (Project Settings > Capabilities turn on App Sandbox) you have three options:
Add temporary entitlements for the applications you want to use.
Put your scripts in the appropriate directory in ~/Library/Application Scripts/ and use NSUserAppleScriptTask.
Implement an AppleScriptObjC bridge and run the AppleScript code from the ASOC framework (requires also an Objective-C bridging header file).
In a sandboxed app NSAppleScript refuses to work.

Swift/AppleScript: Cannot run apple script from Swift code

I try to run AppleScript command from Swift code like this:
var appleScriptCmd = "tell application \"System Events\" to make login item at end with properties {path:\"" + appPath + "\", hidden:false, name:\"Some App\"}";
var appleScriptCmd2 = "tell application \"System Events\" to set visible of process \"Safari\" to false";
and then I have tried both:
let script = NSAppleScript(source: appleScriptCmd2)!;
var errorDict : NSDictionary?
script.executeAndReturnError(&errorDict)
if errorDict != nil { print(errorDict!) }
or older approach:
Process.launchedProcess(launchPath: "/usr/bin/osascript", arguments: ["-e", appleScriptCmd])
neither works and simultaneously both commands I have tried are working from Terminal program using osascript -e "some command" tool.
Since your app is sandboxed (Project Settings > Capabilities turn on App Sandbox) you have three options:
Add temporary entitlements for the applications you want to use.
Put your scripts in the appropriate directory in ~/Library/Application Scripts/ and use NSUserAppleScriptTask.
Implement an AppleScriptObjC bridge and run the AppleScript code from the ASOC framework (requires also an Objective-C bridging header file).
In a sandboxed app NSAppleScript refuses to work.

Add git commit SHA to iOS application

I want to show the current git SHA of when my project was built in my App. What is a good way of doing this in an iOS project with minimal effort?
Version 2.17. Build a85b242.
If you want to add a pretty versioning like this above, just follow these steps:
Open Build Phases in Xcode
Press Add Build Phase
Press Add Run Script Build Phase. You can find this in the top menu Editor. Drag script-line to the position after Target Dependencies.
Set Shell line to /bin/sh
Set the script below to the Script field. Don't forget to change Sources to your path-to-file, where GitVersion.h should be. For example:
version=$(git rev-parse --verify HEAD | cut -c 1-7)
curdate=$(date +"%d.%m.%y")
filesource="//\n// GitVersion.h\n//\n// Created by sig on $curdate.\n//\n\n#ifndef GitVersion_h\n#define GitVersion_h\n\n#define GIT_SHA_VERSION #\"$version\"\n\n#endif"
cd ${SOURCE_ROOT}/${PROJECT_NAME}
echo -e "$filesource" > Sources/GitVersion.h
touch Sources/GitVersion.h
Import GitVersion.h file into Xcode project
Paste these lines:
NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
NSString *version = [info objectForKey:#"CFBundleShortVersionString"];
NSString *app_version = [NSString stringWithFormat:#"Version %#. Build %#.", version, GIT_SHA_VERSION];
NSLog(#"app_version : %#", app_version);
Fully documented answer with images and described advantages could be found here.
You can do it in Schemes. Open your scheme (edit), expand Build in your scheme, click on Pre-Actions, click on + button, select New Run Script Action and write some script which gets SHA and modifies some header file where you can put SHA (easiest way is #define GIT_SHA #"...") and use GIT_SHA in your app in a place where you can display it.
For Swift
Git log format link
Other Swift Flags
Run Script
version=$(git rev-parse --verify HEAD | cut -c 1-10)
commitDate=$(git log -n 1 HEAD --pretty=format:"%h - %cd" | cut -c 12-)
filesource="//\n// GitVersion.swift\n//\n// Commit Date:$commitDate\n//\n\n#if DEBUG\nlet gitVersion = \"$version\"\n#endif"
cd ${SOURCE_ROOT}/${PROJECT_NAME}
echo -e "$filesource" > GitVersion.swift
touch GitVersion.swift
GitVersion.swift
//
// GitVersion.swift
//
// Commit Date: Tue Jun 19 11:09:55 2018 +0900
//
#if DEBUG
let gitVersion = "2fd2f0315d"
#endif
For Swift Projects
Source: https://github.com/ankushkushwaha/AppVersionInXcode
Add build script Run Script
#/bin/sh
version=$(git rev-parse --verify HEAD | cut -c 1-7)
fileContent="// DO NOT EDIT,
// IT IS A MACHINE GENERATED FILE
// AppInfo.swift
//
import Foundation
class AppInfo {
let version: String
let build: String
let gitCommitSHA: String = \"$version\"
init?() {
guard let version = Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String,
let build = Bundle.main.infoDictionary?[\"CFBundleVersion\"] as? String else {
return nil
}
self.version = version
self.build = build
}
}"
echo "$fileContent" > AppInfo.swift
Move/Drag the run script above the 'compile sources'
Now Build your project, It will create a file AppInfo.swift in project's root folder
Drag an drop AppInfo.swift file into your Xcode project navigator.
Use as below
guard let info = AppInfo() else {
return
}
let infoText = "AppVersion: (info.version) \nBuild: (info.build) \nGit hash: (info.gitCommitSHA)"
print(infoText)
Very late answer, but for those who needs to get Git Commit SHA, here is an easy solution:
Select the Target that you want to get the Git Commit SHA for. Then Go to the Build Phase.
1- Create a New Run Scrip Phase by pressing the + button and Add the following script:
git_version=$(git log -1 --format="%h")
info_plist="${SRCROOT}/{THE_PATH_TO_PLIST_FILE}/Info.plist"
/usr/libexec/PlistBuddy -c "Set :GIT_VERSION '${git_version}'" "${info_plist}"
remember to replace {THE_PATH_TO_PLIST_FILE} with the real path to your plist file.
3- Now Go to the Info.plist for the same Target and add a new property named: GIT_VERSION. The script will set the GitVersion to this property.
4- Read the GIT_VERSION from Info.plist in code.
Inspired by: this post
This link worked for my case, but I would just add that it is a nice thing to add the project path and the folder where this auto generated class is put. So in my case it is:
echo "$fileContent" > ${SRCROOT}/MyProject/Models/AppInfo.swift
Here is a nice post about relative paths:
Relative paths on Xcode scripts