swiftfile-uploadsftpwebfaction

Sending CSV file with SFTP in swift


I have a server hosted with webfaction that I would like to be able to send a csv file to from my app with FTP or SFTP. I have found many libraries that should help like ConnectionKit, NMSSH, DLSFPT, and LxFTPRequest. However, all of them are in objective-c and not swift which makes them hard to read, understand, and implement in Swift 4. I have tried to implement LXFTPRequest since I found a swift implementation for the upload and here is my code:

    let fileName = "user-data.csv"
    guard let path = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).first else {fatalError(ErrorMessageStrings.couldntAccessDocs.rawValue)}
    let fileURL = path.appendingPathComponent(fileName)

    let folderLocation = "/home/path/"
    let uploadUrl = URL(string: "ftp://server-name.webfaction.com" + folderLocation)

    let request = LxFTPRequest.upload()
    request?.serverURL = uploadUrl
    request?.localFileURL = fileURL
    request?.username = "username"
    request?.password = "password"

    request?.successAction = { (resultClass, result) in
        print("File uploaded")
    }

    request?.failAction = { (domain, error, errorMessage) in
        print(error)
        print(errorMessage?.description)
        fatalError("Connection could not be made. Action was not completed.")
    }

    request?.progressAction = {(_ totalSize: Int, _ finishedSize: Int, _ finishedPercent: CGFloat) -> Void in
        print(finishedPercent)
    }

    request?.start()`

Using this I almost get it to work but I end up with a 550 error "Requested action not taken. File unavailable (e.g., file not found, no access)." Looking through webfaction documentation I get the feeling that I can only send files through SFTP, which this framework doesnt support.

The doc says "To connect with FTP (for shell users only), substitute the connection type with FTP and the port number with 21." I am assuming since I am sending data from my app it does not count as a shell user and so FTP doesn't grant me access (I may be wrong here). If that is the case how would I go about using the other libraries to send my file over SFTP using Swift and not objective-c?


Solution

  • I ended up using NMSSH and using it in Swift it wasn't as complicated as I thought.

     let session = NMSSHSession.init(host: serverHost, port: xx, andUsername: serverUsername)
        session.connect()
        if session.isConnected{
            session.authenticate(byPassword: serverPasswordString)
            if session.isAuthorized == true {
                let sftpsession = NMSFTP(session: session)
                sftpsession.connect()
                if sftpsession.isConnected {
                    sftpsession.writeFile(atPath: csvFileURL.path, toFileAtPath: folderLocation)
                }
            }
        }