简体   繁体   English

如何使用 Swift 脚本在 macOS 的 iCloud Drive 中获取当前目录?

[英]How to get the current directory in iCloud Drive of macOS with Swift script?

I write Swift scripts to solve small tasks in using macOS.我编写 Swift 脚本来解决使用 macOS 的小任务。
I now need to get the current directory in my script.我现在需要在我的脚本中获取当前目录。

The following program takes the path of the current directory as a string and converts it to an URL.以下程序将当前目录的路径作为字符串并将其转换为 URL。

// myscript.swift
import Foundation

let path = FileManager.default.currentDirectoryPath
let url = URL(string: path)

print("path:", path)
print("url :", url)

When I ran it in ~/Downloads , I was able to get the URL of the current directory correctly.当我在~/Downloads中运行它时,我能够正确获取当前目录的 URL 。
The same was true for the other directories.其他目录也是如此。

$ cd ~/Downloads
$ swift myscript.swift
path: /Users/myname/Downloads
url : Optional(/Users/myname/Downloads)

However, when I ran this program in iCloud Drive directory, I could not get the URL.但是,当我在 iCloud Drive 目录中运行此程序时,我无法获得 URL。

$ cd ~/Library/Mobile\ Documents/com\~apple\~CloudDocs/MyScripts
$ swift myscript.swift
path: /Users/myname/Library/Mobile Documents/com~apple~CloudDocs/MyScripts
url : nil

Is there any way to solve this?有没有办法解决这个问题?
I would like to solve this in order to handle files in iCloud Drive with my Swift scripts.我想解决这个问题,以便使用我的 Swift 脚本处理 iCloud Drive 中的文件。

Thanks.谢谢。

(I used a translation tool to ask this question.) (我用翻译工具来问这个问题。)

You need to encode the string since it contains a space您需要对字符串进行编码,因为它包含一个空格

path = "/Users/myname/Library/Mobile Documents/com~apple~CloudDocs/MyScripts"
if let encoded = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
   let url = URL(string: encoded) {
    print(url)
}

/Users/myname/Library/Mobile%20Documents/com~apple~CloudDocs/MyScripts" /Users/myname/Library/Mobile%20Documents/com~apple~CloudDocs/MyScripts"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM