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.
Related
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
}
}
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
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.
Is it possible to execute a binary located inside a macOS app's sandbox container?
As a test, I tried using Process() to run the PHP binary. This works fine when running the PHP found at usr/bin/php but if I copy that into the app's sandbox container, it won't run. The error is launch path not accessible.
Steps to demonstrate the issue:
Put this in a bare sandboxed app's ViewController:
let path = "/usr/bin/php"
let process = Process()
process.launchPath = path
process.arguments = ["-v"]
process.launch()
Result in the console:
PHP 7.1.16 (cli) (built: Apr 1 2018 13:14:42) ( NTS )
Change the path in the code above, to:
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = documentsURL.absoluteString + "php"
print(path)
The correct path is printed to the console:
file:///Users/myuser/Library/Containers/com.domain.SandboxedApp/Data/Documents/php
Copy the PHP binary to the container:
$ cp /usr/bin/php /Users/myuser/Library/Containers/com.domain.SandboxedApp/Data/Documents
The resulting error in the console:
2018-07-01 20:08:30.630442+1200 SandboxedApp[43579:20898286] Failed to set (contentViewController) user defined inspected property on (NSWindow): launch path not accessible
Why won't Process() run PHP from the container? And why such a weird error message?
(nb you could ask why I would want to do this. There are several reasons eg I would like to understand more deeply how the sandbox permissions work; I would like to sandbox an app which is able to run user-supplied binaries not provided by macOS nor distributed in the app's bundle — yes, not intended for distribution on the MAS, I know this breaks their terms).
I'm trying to build a GUI application for Mac OS X [El Capitan 10.11.1] using Swift [swift --version prints: Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)], which is able to use my shell and ruby scripts.
The problem I'm having is that when I run a script (either .sh or .rb) using NSTask and NSBundle.mainBundle().pathForResource, the called script doesn't see required scripts from the same directory. It works when I'm using a hardcoded 'external' directory, but that's not an options since the scripts have to be a part of the final build.
I have also tried using relative paths such as './Contents/Resources/...' which didn't work.
(Relevant code below. I hope it's enough. Also, as additional information, I'm not a seasoned programmer and I'm rather new (roughly three months) to Mac, Bash & Ruby and very new (as in started this week) to Xcode 6.4, Swift & Cococa and have never used Objective-C, so apologies for poor style and/or very basic errors)
Swift Code:
class ShellTask {
var filePath: String
var arguments: [String]
init(filePath: String, arguments: [String]) {
self.filePath = filePath
self.arguments = arguments
}
func run() {
let task = NSTask()
task.launchPath = filePath
task.arguments = arguments as [String]
task.launch()
task.waitUntilExit()
}
}
class ViewController: NSViewController {
let shellTask = ShellTask(filePath: "", arguments: [""])
#IBAction func buttonDebug(sender: AnyObject) {
let mainBundle = NSBundle.mainBundle()
let resourceDataPath = mainBundle.pathForResource("test", ofType: ".sh")
shellTask.setFilePath(resourceDataPath!)
shellTask.run()
}
Shell/Ruby Code I'm currently using for testing (actual scripts are too much to post right now):
test.sh (entry-point):
#!/usr/bin/env bash
WORKDIR=$(dirname $0)
cd "$WORKDIR"
echo "from: test.sh"
ruby test1.rb
exit
test1.rb:
#!/usr/bin/env ruby
require './test2'
def test1()
puts "from: test1.rb"
end
test1()
test2()
test2.rb:
#!/usr/bin/env ruby
def test2()
puts "from: test2.rb"
end
Output when running test.sh from terminal:
<user>$ bash test.sh
from: test.sh
from: test1.rb
from: test2.rb
Output when running from Cocoa app:
ruby: No such file or directory -- test1.rb (LoadError)
I've been trying several things for the past two days and read multiple threads, but can't find a solution. But it works without problems when using hardcoded paths, such as '/User/user/Documents/Testfiles/test.sh'.
Also, it's ok if the Xcode terminal doesn't print anything from the test files, it just has to find them. For the actual program, the ruby scripts just have to use functions from modules in different files, which are needed in several scripts, so copy-pasting them in each of the called script would be very annoying later on, when changes have to be made. But surely, there has to be a way to get this here running :/
Thanks in advance
edit1:
Using a relative path with NSFileManager.defaultManager().currentDirectoryPath and then adding the path to the resource folder ('/Contents/Resources/test.sh') gives error 'launch path not accessible'.