قالب وردپرس درنا توس
Home / IOS Development / Swift Tip: Use AppKit from the command line

Swift Tip: Use AppKit from the command line



In Swift it is very easy to write a command-line program. As a simple example, paste the following into a file called wc.swift :

  while leaving line = readLine () {
print (line.split (separator: "") .count)
}

This will print the number of words on each line. For example, we can use it on its own:

  $ cat wc.swift | swift wc.swift
6
3
1

On Mac, we are not limited to console input and output. We can also run an entire Mac app directly from the command line. When we import AppKit, we can access the shared program, set a delegate and run the program.

For example, save the following code to a file named spell.swift :

  AppKit

let app = NSAapplication.shared

Class AppDelegate: NSObject, NSApplicationDelegate {
leave the window = NSWindow (contentRect: NSMakeRect (200, 200, 400, 200),
style mask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered,
postpone: false,
screen: null)

func applicationDidFinishLaunching (_ Notification: Notification) {
window.makeKeyAndOrderFront (null)
leave the field = NSTextView (frame: window.contentView! .bounds)
field.backgroundColor = .white
field.isContinuousSpellCheckingEnabled = true
window.contentView? .addSubview (field)
DispatchQueue (label: "background"). Async {
mens la str = readLine (strippingNewline: false) {
DispatchQueue.main.async {
field.textStorage? .append (NSAttributedString (string: str))
}
}
app.terminate (self)
}
}
}

la delegate = AppDelegate ()
app.delegate = delegate
app.run ()

From the terminal we can now run swift spell.swift and the app will read lines from the default input and add them to a text box that has spell check enabled. This particular example may be stupid, but with all AppKit available, the possibilities are almost infinite.

For example, we can use the Open panel to ask the user about a file:

  // select.swift
import appkit

func selectFile () -> URL? {
la dialog = NSOpenPanel ()
dialog.allowedFileTypes = ["jpg", "png"]
watch dialog.runModal () == .OK other {return nil}
return dialog.url
}

print (selectFile ()?. absoluteString ?? "")

Similarly, we can write scripts with a GUI to preview images, process images, find a webpage URL using WKWebView and so on.

In other words, we can easily spray some GUI elements on our command line script when it's more convenient than relying on the command line alone.

To learn more, Swift Talk Episode 22 shows how to write simple command-line tools that utilize frames like Foundation and Cocoa.

To see, become a subscriber. 🙂


Source link