我无法理解如何从目录“ABC”下载所有文件?
import UIKit
class ViewController: UIViewController, NSURLConnectionDataDelegate, UIDocumentInteractionControllerDelegate {
var filePath: String!
var fileStream: NSOutputStream!
var request: NSURLRequest!
var connection: NSURLConnection!
var data: NSMutableData = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startDownload(sender: AnyObject) {
//这里ABC是包含多个pdf、xml和png文件的目录。
let ftpStringUrl = "ftp://username:password@X.XXX.XXX.XXX:21/ABC/"
let urlString = ftpStringUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
// First get and check the URL.
let url: NSURL! = NSURL(string: urlString!)
let success = (url != nil)
// If the URL is bogus, let the user know. Otherwise kick off the connection.
if (!success) {
NSLog("Invalid URL");
} else {
NSLog("Valid URL");
request = NSURLRequest(URL: url)
connection = NSURLConnection(request: request, delegate: self)
}
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
print(response);
}
func receiveDidStopWithStatus(statusString: String?){
}
func stopReceiveWithStatus(statusString: String?) {
print(data.length)
if (self.connection != nil) {
self.connection.cancel()
self.connection = nil
}
if (self.fileStream != nil) {
self.fileStream.close()
self.fileStream = nil
}
self.receiveDidStopWithStatus(statusString);
self.filePath = nil;
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.data.appendData(data)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
self.stopReceiveWithStatus("Connection failed")
print("connection failed....")
}
func connectionDidFinishLoading(connection: NSURLConnection) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let filePath = documentsPath.stringByAppendingPathComponent("")
data.writeToFile(filePath, atomically: true)
print("\(filePath)")
self.stopReceiveWithStatus(nil)
}
}
有什么方法可以从目录“ABC”下载多个不同格式的文件吗? 提前致谢。
最佳答案
我可能是错的,但我认为使用 NSURLConnection 或 NSURLSession 获取 FTP 目录列表是不可能的。您可能必须使用 CFFTPStream 才能发出任意 FTP 命令(例如 LIST)。
之后,您只需为每个文件发出一个正常的 URL 加载请求(使用 NSURLConnection 或 NSURLSession)。
或者,如果您可以控制服务器上的数据,您可以考虑以下替代方案之一:
- 转到 HTTP 和 WebDAV,然后发送 PROPFIND 请求。
- 提供一个 list 文件,其中包含您需要检索的所有文件的列表。
- 将数据存储在 ZIP 存档中并在客户端解压缩。
关于ios - 如何在 ios swift 中使用 nsurlconnection 从 FTP 服务器下载包含多个文件的完整目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35993729/