问题
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