在代码中为Mac OS X上的给定文件扩展名设置默认应用程序,可以使用以下方法:
LaunchServices
框架:import Foundation
import LaunchServices
func setDefaultApplication(forExtension ext: String, bundleID: String) -> Bool {
let ext = ext as CFString
let bundleID = bundleID as CFString
let error = LSSetDefaultHandlerForURLScheme(ext, bundleID)
return error == noErr
}
let extension = "txt"
let bundleID = "com.apple.TextEdit"
let success = setDefaultApplication(forExtension: extension, bundleID: bundleID)
if success {
print("成功设置\(extension)文件的默认应用为\(bundleID)")
} else {
print("设置失败")
}
duti
命令行工具:import Foundation
func setDefaultApplication(forExtension ext: String, bundleID: String) -> Bool {
let task = Process()
task.launchPath = "/usr/bin/duti"
task.arguments = ["-s", bundleID, ext]
task.launch()
task.waitUntilExit()
return task.terminationStatus == 0
}
let extension = "txt"
let bundleID = "com.apple.TextEdit"
let success = setDefaultApplication(forExtension: extension, bundleID: bundleID)
if success {
print("成功设置\(extension)文件的默认应用为\(bundleID)")
} else {
print("设置失败")
}
这两种方法都可以实现为Mac OS X上的给定文件扩展名设置默认应用程序。使用LaunchServices
框架的方法需要导入Foundation
和LaunchServices
模块,而使用duti
命令行工具的方法则需要导入Foundation
模块。
领取专属 10元无门槛券
手把手带您无忧上云