且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Swift将文件上传到FTP服务器

更新时间:2023-09-12 10:18:10

以下是示例

此代码已在Swift 2.0上经过全面测试

This code is fully tested on Swift 2.0

 let file = "SomeFile.txt"
        if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
           //path will be stored here
            let sPath = dir.stringByAppendingPathComponent(file);

      print(sPath) //  printing the file path
        }

无法执行上传

根据有关将字符串转换为NSURL的评论进行修改

EDIT AS ASKED IN COMMENT ABOUT CONVERTING STRING TO NSURL

let URL: NSURL = NSURL(string: stringofURL)! //replace stringofURL to sPath

更新您的代码

UPDATED YOUR CODE

let file = "myFile.txt"
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
    //path will be stored here
    let sPath = dir.stringByAppendingPathComponent(file);
    print(sPath) //  printing the file path

    let url: NSURL = NSURL(string: sPath)!

    let destinationFile = "myFile.txt"
    session.upload(url, path: destinationFile) { // here was the error it should be session not FTPsession
        (result, error) -> Void in
        print("- Result:\n\(result), error: \(error)\n\n")
    }
}