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

问题描述:

我正在使用框架RebekkaTouch将文件从我的Swift应用程序上传到FTP服务器,就像:

I'm using a framework RebekkaTouch to upload files from my Swift app to an FTP server, just like:

if let URL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "txt") {
    let path = "myFile.txt"
    session.upload(URL, path: path) {
        (result, error) -> Void in
        print("result:\n\(result), error: \(error)\n\n")
    }
}

这非常适合我通过Xcode手动上传的文件.但是我似乎无法找到我下载并动态存储在本地Documents目录中的文件的文件路径.

This works great for files I manually upload via Xcode. But I don't seem to be able to find the file path for file I download and store locally on the Documents directory dynamically.

说,我知道我有这个文件:/private/var/mobile/Containers/Data/Application/3D92EA55-01E0/Documents/SomeFile.txt

Say, I know I have this file: /private/var/mobile/Containers/Data/Application/3D92EA55-01E0/Documents/SomeFile.txt

我知道它在那里,因为我在遍历NSFileManager.defaultManager()之后就得到了路径,但是我无法将其转换为NSURL,所以我可以上传它.

I know it's there because I get the path after looping through NSFileManager.defaultManager() but I can't convert it no NSURL so I can upload it.

有什么想法吗?

////更新

这是死的地方

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"
    FTPSession.upload(url, path: destinationFile) { // <-- Dies here
        (result, error) -> Void in
        print("- Result:\n\(result), error: \(error)\n\n")
    }
}

以下是示例

此代码已在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")
    }
}