快速测量上传速度

时间:2019-12-16 09:42:00

标签: ios swift upload

我有自己的服务器,我想在其中将文件上传到Swift中。我也想衡量上传速度。在下面,我创建一个空的1 mb数据对象并将其上传。

        let urlString = "https://myserver/upload.php"
        guard let url = URL(string: urlString) else {
            return
        }

        var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
        urlRequest.httpMethod = "POST"
        urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let emptyData = createEmptyData(of: 1048576)

        let json = ["file" : emptyData]
        urlRequest.httpBody = try? JSONEncoder().encode(json)

        let sessionConfiguration = URLSessionConfiguration.ephemeral
        let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)

        session.dataTask(with: urlRequest).resume()

如何测量上传速度?谢谢

2 个答案:

答案 0 :(得分:1)

label1.Text = $"Score: {score} #comment | Speed: {speed} #endcomment";

答案 1 :(得分:1)

为什么不只在方法开始时使用Core Foundation的绝对时间方法,而是在完成文件上传后从方法结束时的绝对时间中减去该值。

func uploadData(){
        let start = CFAbsoluteTimeGetCurrent()
        var uploadTask: URLSessionUploadTask!

//Code for uploading file

        uploadTask = session.uploadTask(with: urlRequest, from: emptyData) { (data, response, error) in
        if let err = error {
            //There's an error
        }
        else if let response = response {
            //check for response status
        }

       //Once upload is complete
       let totalUploadTime = CFAbsoluteTimeGetCurrent() - start
      }





}