4

I know a Java app can be bundled as a Mac app with the user-interface driven by Java Swing or JavaFX, and a Java runtime (JRE) bundled. But I want to build a native app in Xcode written in Swift with a Cocoa user-interface that calls upon a Java library to process some data.

I need to invoke the bundled JRE, call the desired library (JAR file), pass a reference to a file in the Mac’s storage (or else the file’s content as a large String in memory), and get back a string (XML or CSV or tab-delimited data).

This Question is similar to this Question but updated for Swift and the modern macOS and Java 8.

1 Answer 1

4

Unless you want all the pain involved in communicating directly in memory through something like JNI, the only way is to launch an external process using NSTask (for example) reading/writing a file or reading standard out.

If all the Java components are in your .app, you can directly reference the bundled JRE and program JAR.

/Applications/MyApp.app/.../java -jar /Applications/MyApp.app/.../MyAppJar.jar 

Not sure how you are planning on bundling the JRE, since this will not be a Swing app. Maybe you would use appbundler to make a fake Swing .app, then just copy the file structure over to your native app.

If so, keep in mind that you will probably have to manually copy over bin/java, since appbundler doesn't included automatically.

Sign up to request clarification or add additional context in comments.

8 Comments

should I embed java also in by app bundle?
Update: Java 9 is now modularized. See the jlink tool and spec, a linker for Java. This means a smaller runtime size to be bundled with your app. Other link-time optimizations can be put in place as well for faster performance.
@LOG_TAG Yes, you can build an entire iOS app in Java, and distribute the app on the Apple App Store. Oracle has spun-off JavaFX as an open-source project now hosted and led by Gluon. See OpenJFX.io. You can use the latest Java 11 & 12.
@LOG_TAG No, nothing about JavaFX has to do with calling native code, it is a GUI toolkit.
@LOG_TAG Java Native Access (JNA) is an easier alternative to JNI for calling native code from Java. But that is the opposite direction of this Question, which asks for calling Java code from native code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.