我制作了一个Swift菜单栏应用程序XCode 8.2.1。此脚本中的菜单栏选项之一成功运行了我创建的AppleScript。我想在此菜单栏应用程序中添加另一个选项,以为用户打开PDF指令/自述文件。如何在Swift中打开本地保存的PDF文件?
我已将XCode的AppDelegate.swift文件中包含的代码包含在内。
//
// AppDelegate.swift
// Layout Ad
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
@IBAction func quitClicked(sender: NSMenuItem) {
NSApplication.shared().terminate(self)
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
statusItem.menu = statusMenu
let icon = NSImage(named: "statusIcon")
//icon?.isTemplate = true // best for dark mode
statusItem.image = icon
statusItem.menu = statusMenu
constructMenu()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
//Function to get the path to the applescript
func runApplescript(){
let task = Process()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["/Library/Scripts/1_Page Layout Scripts/Layout Ad.scpt"]
task.launch()
}
//Function to open the script's instructions
func openPDF(){
//Code to open PDF file will go here
//"/Volumes/NAS/Advertising Department/16_SCRIPTS/*Instructions/2_Running Scripts/1_InDesign/Layout Ad Script Instructions.pdf"
}
//Function to make the menu work
func constructMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Script Instructions", action: #selector(openPDF), keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Layout Ad", action: #selector(runApplescript), keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
}
}
答案 0 :(得分:0)
NSWorkspace
可以做到。
let url = URL(fileURLWithPath: "/Volumes/NAS/Advertising Department/16_SCRIPTS/*Instructions/2_Running Scripts/1_InDesign/Layout Ad Script Instructions.pdf")
NSWorkspace.shared.open(url)