快速测量上传速度



我有自己的服务器,我想在 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
})
}

为什么不在方法开始时使用 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
}


}

最新更新