Upload file to FTP server with Swift

余生颓废 提交于 2019-12-24 15:48:41

问题


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

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.

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

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.

Any ideas?

////UPDATE

This is where is dies:

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

回答1:


Here is the example

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
        }

than you can perform the upload

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


来源:https://stackoverflow.com/questions/34335867/upload-file-to-ftp-server-with-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!