Swift Requires Chilkat v11.0.0+
Swift
SFTP Read Directory Listing
See more SFTP Examples
Demonstrates how to download a directory listing and iterate over the files.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Important: It is helpful to send the contents of the
// sftp.LastErrorText property when requesting support.
let sftp = CkoSFtp()!
// Set some timeouts, in milliseconds:
sftp.connectTimeoutMs = 5000
sftp.idleTimeoutMs = 10000
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
var hostname: String? = "www.my-sftp-server.com"
var port: Int = 22
success = sftp.connect(hostname: hostname, port: port)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// Authenticate with the SSH server. Chilkat SFTP supports
// both password-based authenication as well as public-key
// authentication. This example uses password authenication.
success = sftp.authenticatePw(login: "myLogin", password: "myPassword")
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// After authenticating, the SFTP subsystem must be initialized:
success = sftp.initializeSftp()
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// Open a directory on the server...
// Paths starting with a slash are "absolute", and are relative
// to the root of the file system. Names starting with any other
// character are relative to the user's default directory (home directory).
// A path component of ".." refers to the parent directory,
// and "." refers to the current directory.
var handle: String? = sftp.openDir(path: ".")
if sftp.lastMethodSuccess == false {
print("\(sftp.lastErrorText!)")
return
}
// Download the directory listing:
let dirListing = CkoSFtpDir()!
success = sftp.readDirListing(handle: handle, dirObj: dirListing)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// Close the handle for the directory listing.
success = sftp.closeHandle(sftpHandle: handle)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
// Iterate over the files.
let fileObj = CkoSFtpFile()!
var i: Int = 0
var n: Int = dirListing.numFilesAndDirs.intValue
while i < n {
success = dirListing.file(at: i, fileObj: fileObj)
if success == false {
print("\(dirListing.lastErrorText!)")
return
}
print("\(fileObj.filename!)")
print("\(fileObj.fileType!)")
print("Size in bytes: \(fileObj.size32.intValue)")
print("----")
i = i + 1
}
print("Success.")
}