ios - 快速测量上传速度

标签 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()

如何测量上传速度?谢谢

最佳答案

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

     var timer: Timer?
     var uploadTask: URLSessionUploadTask!

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

     let emptyData = Data.init(capacity: 102454)

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

     let sessionConfiguration = URLSessionConfiguration.ephemeral
     let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
     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
        }

        //Stop the timer here
        timer?.invalidate()
      }

    uploadTask.resume()
    calculateSpeed()
}


func calculateSpeed() {
    var previousBytesSent: Int64 = 0
    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (_) in
        let bytesSent = uploadTask.countOfBytesSent
        let speed =  abs(bytesSent-previousBytesSent)
        //Here you get the speed in Bytes/sec
        previousBytesSent = bytesSent
    })
}

关于ios - 快速测量上传速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59353972/

相关文章:

mysql - 将内容管理系统网站上传到互联网

ios - 如何从 swift 文件调用用 Objective C 编写的 Web 服务

ios - 为什么我的 Alamofire 路由器没有给我正确的 URL 请求?

ios - 添加UIDatePicker后,打印错误

SwiftUI 滚动/列表滚动事件

html 上传 : localize browse button

android - 使用相机拍照后自动上传照片到Phonegap

iOS UIView 3D 旋转和 subview

ios - 使用导致崩溃的电话号码在 iOS 上使用 Firebase 进行 Swift 身份验证

ios - SCLAlertView - 如何格式化 addTextField - 电话号码