swiftmacosftpfileprovider

Swift macOS How to Implement FTP Support


I need to upload a file to an FTP server, check if a folder exists and, if not, create it. I found FileProvider by Amir Abbas Mousavian. I got everything installed and have implemented the following code:

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)")
    }
})

When I run the code, the completionHandler for contentsOfDirectory never fires. Does anyone know what I'm doing wrong or have some other way I can do the FTP functions I need to?


Solution

  • Your closure is not being called because ftpProvider is nil, a quick look at the source code tells us that the url sent to the init needs to contain the protocol. So add "ftp" or "ftps" to your url.

    And wrap the init in a guard statement

    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