【问题标题】:What is the best way to make download speed test app using swift3?使用 swift3 制作下载速度测试应用程序的最佳方法是什么?
【发布时间】:2017-03-20 16:38:21
【问题描述】:

我正在使用从这个问题Right way of determining internet speed in iOS 8 截取的以下代码在我的应用程序中进行速度测试,但是当进行测试并与速度测试工具http://www.speedtest.net/ 进行比较时,我的应用程序的结果小于 speedTest。如果我的应用程序速度结果为 1mbps,则 speedtest.net 结果为 2mbps 或更多

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDataDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    testDownloadSpeedWithTimout(5.0) { (megabytesPerSecond, error) -> () in
        print("\(megabytesPerSecond); \(error)")
    }
}

var startTime: CFAbsoluteTime!
var stopTime: CFAbsoluteTime!
var bytesReceived: Int!
var speedTestCompletionHandler: ((megabytesPerSecond: Double?, error: NSError?) -> ())!

func testDownloadSpeedWithTimout(timeout: NSTimeInterval, completionHandler:(megabytesPerSecond: Double?, error: NSError?) -> ()) {
    let url = NSURL(string: "http://insert.your.site.here/yourfile")!

    startTime = CFAbsoluteTimeGetCurrent()
    stopTime = startTime
    bytesReceived = 0
    speedTestCompletionHandler = completionHandler

    let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
    configuration.timeoutIntervalForResource = timeout
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    session.dataTaskWithURL(url).resume()
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
    bytesReceived! += data.length
    stopTime = CFAbsoluteTimeGetCurrent()
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    let elapsed = stopTime - startTime
    guard elapsed != 0 && (error == nil || (error?.domain == NSURLErrorDomain && error?.code == NSURLErrorTimedOut)) else {
        speedTestCompletionHandler(megabytesPerSecond: nil, error: error)
        return
    }

    let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
    speedTestCompletionHandler(megabytesPerSecond: speed, error: nil)
}

}

【问题讨论】:

    标签: swift3 ios8.1


    【解决方案1】:

    我把我的文件放在不同的服务器上,每个都给我不同的结果,所以问题是速度结果取决于你下载的服务器,解决方案是将文件放在多台服务器上,并为客户端检测最佳服务器并从中下载。

    【讨论】:

      【解决方案2】:

      您的代码似乎使用单线程测试速度,这可能是它测量结果较低的主要原因之一。

      Speedtest.net 和我们这样的大多数测试人员也使用多线程方法。这是估算 Internet 链路容量的更好方法。

      您可以在此处找到将执行多线程测量的 iOS SDK:

      https://github.com/speedchecker/speedchecker-sdk-ios

      【讨论】:

      • 多线程如何提高下载速度? CPU 几乎从来都不是瓶颈。当然,我们在这里假设服务器可以使链接饱和。
      • 你说得对,不是 CPU 瓶颈。它关于无法使单个下载线程(或上传)的连接饱和。这种情况在更高的速度上更为明显,例如而 100 Mbit 连接可以用 3 个并行下载线程饱和。 1Gbit 可能需要更多线程才能饱和。在我们的 SDK 中,每次达到 100 Mb/s 的额外增量时,我们都会添加一个额外的线程
      猜你喜欢
      • 2011-06-05
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 2015-10-19
      • 2010-09-12
      相关资源
      最近更新 更多