NSURLSession Upload File To Server Swift

2019-06-06 03:56发布

问题:

I'm creating a Internet Speed testing app and can't seem to get it right to upload the zip file to the ftp server. It is an open server. I want to be able to upload the file and show the progress.

The func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) isn't working.

import UIKit
import Foundation

class Upload: UIViewController, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDelegate {

    let url: NSURL = NSURL(string: "ftp://speedtest.tele2.net/upload")!
    let path = NSBundle.mainBundle().pathForResource("2MB", ofType: "zip")

    func Test() {
        let data: NSData = NSData(contentsOfFile: path!)!

        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
        request.timeoutInterval = 10.0
        request.HTTPBody = data

        let session: NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
        let task: NSURLSessionUploadTask = session.uploadTaskWithRequest(request, fromData: data)

        task.resume()
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        print("\(totalBytesSent)/\(totalBytesExpectedToSend)")
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        print(error)
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
        completionHandler(NSURLSessionResponseDisposition.Allow)
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        //
    }

}

回答1:

Have you read the documentation properly. If you look at the documentation for this method,

   func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

This method is optional unless you need to support the (relatively obscure) multipart/x-mixed-replace content type. With that content type, the server sends a series of parts, each of which is intended to replace the previous part. The session calls this method at the beginning of each part, and you should then display, discard, or otherwise process the previous part, as appropriate.

If you do not provide this delegate method, the session always allows the task to continue.

Here, https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSURLSessionDataDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDataDelegate/URLSession:dataTask:didReceiveResponse:completionHandler:

You can simply not implement this method or then have to so that it allows further response.

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
    completionHandler(.Allow)
}