Implementing Events in Swift


IPWorks components in Swift use delegate protocols to handle events such as progress updates, errors, and completion notifications. Implementing the appropriate delegate protocol allows your class to respond to these events.

In Swift, events are implemented by conforming to the delegate protocol defined in the component's .swift file.

To implement the protocol, copy the method definitions from the component's delegate protocol (for example, IPWorksFTPDelegateSwift) into your class and provide your own implementations. This approach works for FTP as well as other IPWorks components.

For instance, you could create a class called MyFTPSwiftEvents to handle events from the IPWorksFTPDelegateSwift protocol like this:

class MyFTPSwiftEvents: IPWorksFTPDelegateSwift{
    func onConnectionStatus(connectionEvent: String, _ statusCode: Int32, _ description: String){
    }
    func onDirList(dirEntry: String, _ fileName: String, _ isDir: Bool, _ fileSize: Int64, _ fileTime: String){
    }
    func onEndTransfer(direction: Int32){
    }
    func onError(errorCode: Int32, _ description: String){
    }
    func onPITrail(direction: Int32, _ message: String){
    }
    func onStartTransfer(direction: Int32){
    }
    func onTransfer(direction: Int32, _ bytesTransferred: Int64, _ percentDone: Int32, _ text: NSData){
    }
}

You would then assign an instance of your newly implemented MyFTPSwiftEvents class as a delegate of your IPWorksFTPSwift class:

var ftp = IPWorksFTPSwift()
ftp.delegate = MyFTPSwiftEvents()
ftp.remoteHost = server
ftp.remotePort = port
ftp.user = user
ftp.password = password
ftp.logon()

Note: Swift does not allow other classes to access variables within a class directly. To access variables outside the MyFTPSwiftEvents class from within its event handlers, you must pass an instance of the class into its constructor, as shown below:

class MyFTPSwiftEvents: IPWorksFTPDelegateSwift{
    var main: DetailViewController = DetailViewController()
    init(outer: DetailViewController){
        main = outer
    }
    // other implemented events
}
var ftp = IPWorksFTPSwift()
ftp.delegate = MyFTPSwiftEvents(main: self)

Once you can access the first class within the second class, getter and setter methods can be used to modify variables.

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.