簡體   English   中英

使用Swift將文件上傳到FTP服務器

[英]Upload file to FTP server with Swift

我正在使用RebekkaTouch框架將文件從我的Swift應用程序上傳到FTP服務器,就像:

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目錄上本地下載和存儲。

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

我知道它在那里,因為我在循環通過NSFileManager.defaultManager()之后得到了路徑,但我無法轉換它沒有NSURL所以我可以上傳它。

有任何想法嗎?

//// UPDATE

這就是死亡的地方:

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上經過全面測試

 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的評論中的編輯

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

更新了你的代碼

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")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM