Swift获取网络上行/下行速度
使用Swift实现, 兼容OC
本文章是基于Swift项目编写的示例
1. 单例:
NetSpeed.shared
2. 代理:
NetSpeed.shared.delegate = self
3. 开始测速:
// 默认1秒回调一次
NetSpeed.shared.begin()
// 或者可以自定义回调间隔时间(单位: 秒)
NetSpeed.shared.begin(duration: 2)
4. 停止测速:
NetSpeed.shared.stop()
5. 实现代理
extension ViewController: NetSpeedProtocol {
func didSent(octets: UInt32) {
let upload = "upload \(formatSpeed(octets: octets))"
print(upload)
}
func didReceived(octets: UInt32) {
let download = "download \(formatSpeed(octets: octets))"
print(download)
}
/// 格式化
private func formatSpeed(octets: UInt32) -> String {
var speedString = ""
if octets < 1024 {
speedString = String(format: "%lludB/S", octets)
} else if octets >= 1024 && octets < 1024 * 1024 {
speedString = String(format: "%lluKB/S", octets / 1024)
} else if octets >= 1024 * 1024 {
speedString = String(format: "%lluMB/S", octets / (1024*1024))
}
return speedString
}
}
6. 集成:
pod 'NetSpeed'
// 可以先执行
pod search NetSpeed
// 如果搜索不到, 请执行 pod repo update 之后再 pod search NetSpeed
7. 使用环境:
- cocoaPods 1.11.3
- Swift5+
- iOS 11.0+
8. 开发环境:
参考文献: https://www.jianshu.com/p/1814734b825e
网友评论