【发布时间】:2020-04-08 18:14:25
【问题描述】:
我有自己的服务器,我想用 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()
如何测量上传速度?谢谢
【问题讨论】:
-
速度由距离或大小/时间决定。所以看看上传1Mb需要多长时间
-
@Scriptable 我应该在 URLSessionDelegate 的哪个委托方法中计算上传速度?
-
您不需要委托方法。 session.dataTask 有一个完成处理程序。你可以使用它。
-
@Scriptable 我明白了,谢谢