简体   繁体   中英

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.
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.

// 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.
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.

$ 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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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