【问题标题】:Swift: How to determine application folder?Swift:如何确定应用程序文件夹?
【发布时间】:2023-03-20 05:55:01
【问题描述】:

我刚刚找到了如何在 macOS 下确定文档文件夹。 但我喜欢找到我的二进制文件所在的文件夹。 我想加载一个文件,该文件与我的二进制文件存储在同一目录中。

【问题讨论】:

  • 使用NSBundle.mainBundle().pathForResource

标签: swift macos


【解决方案1】:

2020 | SWIFT 5.1:

let appFolder = Bundle.main.resourceURL

【讨论】:

    【解决方案2】:

    使用以下代码查找应用程序目录:

      let dirPaths = NSSearchPathForDirectoriesInDomains(.ApplicationDirectory,
                    .UserDomainMask, true)
      NSLog("%@", dirPaths.first!);
    

    要查找二进制文件所在的目录,可以很容易地识别为(@vadian 已经建议):

    NSBundle.mainBundle().bundleURL.URLByDeletingLastPathComponent!
    

    【讨论】:

    • 请使用代码 NSLog("%@", NSBundle.mainBundle().bundleURL.URLByDeletingLastPathComponent!)
    • 好的,谢谢。这条线对我有用:let path = NSBundle.mainBundle().bundleURL.URLByDeletingLastPathComponent!.URLByAppendingPathComponent(file)
    【解决方案3】:

    我认为NSBundle.mainBundle() 是您正在寻找的。您可以使用NSBundle.mainBundle().pathForResource("file", ofType: "txt") 来加载文件

    【讨论】:

      【解决方案4】:

      这对我有用(使用 iOS):

      let directoryPaths = NSSearchPathForDirectoriesInDomains(.applicationDirectory, .userDomainMask, true)
              
      if let firstURL = directoryPaths.first, let url = URL(string: firstURL)?.deletingLastPathComponent() {
          print("App files url: \(url.path)")
      }
      

      【讨论】:

        【解决方案5】:

        斯威夫特 5:

        var appURL = URL(fileURLWithPath: Bundle.main.bundleURL.absoluteString)
        
        // Remove app from URL to get directory path
        appURL.deleteLastPathComponent()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-20
          • 2011-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-13
          • 1970-01-01
          • 2014-04-09
          相关资源
          最近更新 更多