使用 NSURLSession 的 iOS FTP 上传

标签 ios ftp nsurlsession

我正在尝试通过 FTP 将文件上传到服务器。根据 Apple Documentation NSURLSession 类支持 FTP 操作。

有一个著名的Apple Developer blog这也支持这一点。但是仍然不清楚 NSURLSession API 是否支持 ftp 上传? (我尝试了建议的方式并收到错误)。

用常规方式CFFTPStreamRef ,ftp 上传工作正常,但在 9.0 中已弃用。标题说:CF_DEPRECATED(10_3, 10_11, 2_0, 9_0 , "Use NSURLSessionAPI for ftp requests")

需要帮助的任何想法、示例或链接。我现在正在尝试这样的事情:

NSURL *url_upload = [NSURL URLWithString:@"ftp://username:password@thelink/myfolder/filename.zip"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url_upload];
    [request setHTTPMethod:@"PUT"];
NSURL *docsDirURL = [NSURL fileURLWithPath:filePath];

NSURLProtectionSpace * protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:url_upload.host port:[url_upload.port integerValue] protocol:url_upload.scheme realm:nil authenticationMethod:nil];

NSURLCredential *cred = [NSURLCredential
                         credentialWithUser:userId
                         password:password
                         persistence:NSURLCredentialPersistenceForSession];


NSURLCredentialStorage * cred_storage ;
[cred_storage setCredential:cred forProtectionSpace:protectionSpace];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.URLCredentialStorage = cred_storage;
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
sessionConfig.allowsCellularAccess = YES;
sessionConfig.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionUploadTask *uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:docsDirURL];
[uploadTask resume];

最佳答案

据我所知,NSURLSession(和 NSURLConnection)支持通过 FTP 检索文件,但不支持任何其他 FTP 命令,例如 STOR(注意 PUT 是一种 HTTP 方法,而不是 FTP 方法)。

为了您的目的,您的选择是使用 CFFTPStream API(几乎不能工作)或停止使用 FTP。

我强烈建议停止使用 FTP。 FTP 协议(protocol)非常不安全,通过网络以明文形式发送用户名和密码,这使得人们很容易嗅探凭据并伪装成用户。因此,如今 FTP 上传甚至可以远程接受的唯一情况是匿名 FTP 上传到共享保管箱,即使这样,它也有些可疑。这就是为什么该功能从未添加到 NSURLConnection API 中,更不用说添加到 NSURLSession 中了。

有很多更好的选择,也更安全,例如基于 HTTPS 的 WebDAV、通过 HTTPS 的 POST 请求上传、WebDAV 或带有摘要身份验证的 POST 请求等。这些替代方法实际上受 NSURLSession 支持,并提供其他优势,例如恢复下载的能力。除非您绝对无法更改服务器端,否则请改用其中一种替代方法。

关于使用 NSURLSession 的 iOS FTP 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926083/

相关文章:

ios - 为什么连接回 iOS 后台 NSURLSession 等待锁定的时间太长,导致应用程序崩溃?

ios - NSMutableURLRequest 设置授权头

iOS Xcode Swift 将输入名字和姓氏组合成全名问题

ios - iPhone X Swift 底部有空白

mysql - Apache、MySQL 和 FTP 'Detected With Wrong Path' 在 Win7 上使用 XAMPP

powershell - 使用 PowerShell 测试 FTP 连接

ios - CollectionView NSURL session 速度和重新加载

jquery - 使用 NSError 处理 WCF REST 服务和 iOS 错误

iphone - coreLocation多久更新一次

java - ftp 从 windows 发送到 linux 显示 java.net.ConnectException