我有自己的服务器,我想把我的文件上传到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()
如何测量上传速度?谢谢
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
})
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。