Swift macOS 如何实现 FTP 支持

Swift macOS How to Implement FTP Support

我需要将文件上传到 FTP 服务器,检查文​​件夹是否存在,如果不存在,则创建它。我找到了 Amir Abbas Mousavian 的 FileProvider。我安装了所有东西并实现了以下代码:

let credential = URLCredential(user: "user", password: "password", persistence: .permanent)
let ftpProvider = FTPFileProvider(baseURL: URL(string:"cflm.org")!, mode: .active, credential: credential, cache: nil)
ftpProvider?.delegate = self as! FileProviderDelegate
ftpProvider?.contentsOfDirectory(path: "/", completionHandler: {
    contents, error in
    for file in contents {
        print("Name: \(file.name)")
        print("Size: \(file.size)")
        print("Creation Date: \(file.creationDate)")
        print("Modification Date: \(file.modifiedDate)")
    }
})

当我 运行 代码时,contentsOfDirectory 的 completionHandler 从不触发。有谁知道我做错了什么或有其他方法可以执行我需要的 FTP 功能?

你的闭包没有被调用,因为 ftpProvider 是 nil,快速查看源代码告诉我们发送给 init 的 url 需要包含协议。因此,将 "ftp" 或 "ftps" 添加到您的 url。

并将 init 包装在 guard 语句中

guard let ftpProvider = FTPFileProvider(baseURL: URL(string:"ftp://cflm.org")!, mode: .active, credential: credential, cache: nil) else {
    return //or some error handling
} 
//... rest of code