[英]Measure upload speed in swift
我有自己的服務器,我想用 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()
如何測量上傳速度? 謝謝
為什么不直接在方法開始時使用 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
}
}
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
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.