开发者社区> 问答> 正文

快速测量上传速度

我有自己的服务器,我想把我的文件上传到SWIFT。我也想测量上传速度。下面我创建一个空的1MB数据对象并上传它。

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

如何测量上传速度?谢谢

展开
收起
游客5akardh5cojhg 2019-12-16 22:24:29 601 0
1 条回答
写回答
取消 提交回答
  • 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
        })
    }
    
    2019-12-16 22:24:58
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载