Swift
Swift
Open a Remote Directory on an SFTP Server
See more SFTP Examples
Demonstrates the Chilkat SFtp.OpenDir method, which opens a remote directory and returns a handle for reading its entries. The only argument is the directory path. Close the handle with CloseHandle when finished.
Background: Listing a directory in SFTP is a handle-based operation, mirroring file access: open the directory to get a handle, read its entries, then close it. The handle is passed to
ReadDirListing to retrieve the names and attributes. As with file handles, the directory handle is a server-side resource that should be closed to avoid exhausting the server's limits.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Demonstrates the SFtp.OpenDir method, which opens a remote directory and returns a handle for
// reading its entries. The only argument is the directory path.
let sftp = CkoSFtp()!
// Connect, authenticate, and initialize the SFTP subsystem.
var port: Int = 22
success = sftp.connect(hostname: "sftp.example.com", port: port)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
var password: String? = "mySshPassword"
success = sftp.authenticatePw(login: "mySshLogin", password: password)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
success = sftp.initializeSftp()
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// Open the remote directory. OpenDir returns a handle string.
var handle: String? = sftp.openDir(path: "subdir")
if sftp.lastMethodSuccess == false {
print("\(sftp.lastErrorText!)")
return
}
print("Opened directory, handle = \(handle!)")
// The directory entries are read with ReadDirListing using this handle.
// Close the handle when finished.
success = sftp.closeHandle(sftpHandle: handle)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
sftp.disconnect()
}