Я хотел бы посмотреть, сколько времени прошло загрузка, и я увидел это link on how to do it , поэтому я немного изменил его (например, изменил переименованные классы и т. Д.), Чтобы работать в Swift 3 . Однако, у меня есть одна проблема на линии: let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
, что я просто не могу исправить, и это сообщение об ошибке продолжает появляться:Невозможно создать экземпляр URLSession в Swift
Argument labels '(configuration:, delegate:, delegateQueue:)' do not match any available overloads
Вот мой код: (Проблемный линия является одна следующая // ВОПРОС о СЛЕДУЮЩАЯ ЛИНИЯ)
import UIKit
class ViewController: UIViewController, URLSessionDelegate, URLSessionDataDelegate {
override func viewDidLoad() {
super.viewDidLoad()
testDownloadSpeedWithTimout(timeout: 5.0) { (megabytesPerSecond, error) ->() in
print("\(megabytesPerSecond); \(error)")
}
}
var startTime: CFAbsoluteTime!
var stopTime: CFAbsoluteTime!
var bytesReceived: Int!
var speedTestCompletionHandler: ((_ megabytesPerSecond: Double?, _ error: NSError?) ->())!
/// Test speed of download
///
/// Test the speed of a connection by downloading some predetermined resource. Alternatively, you could add the
/// URL of what to use for testing the connection as a parameter to this method.
///
/// - parameter timeout: The maximum amount of time for the request.
/// - parameter completionHandler: The block to be called when the request finishes (or times out).
/// The error parameter to this closure indicates whether there was an error downloading
/// the resource (other than timeout).
///
/// - note: Note, the timeout parameter doesn't have to be enough to download the entire
/// resource, but rather just sufficiently long enough to measure the speed of the download.
func testDownloadSpeedWithTimout(timeout: TimeInterval, completionHandler:@escaping (_ megabytesPerSecond: Double?, _ error: NSError?) ->()) {
let url = NSURL(string: "http://insert.your.site.here/yourfile")!
startTime = CFAbsoluteTimeGetCurrent()
stopTime = startTime
bytesReceived = 0
speedTestCompletionHandler = completionHandler
let configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForResource = timeout
////////////////// ISSUE ON NEXT LINE ///////////////////
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
session.dataTaskWithURL(url).resume()
}
func URLSession(session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: NSData) {
bytesReceived! += data.length
stopTime = CFAbsoluteTimeGetCurrent()
}
func URLSession(session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
let elapsed = stopTime - startTime
guard elapsed != 0 && (error == nil || (error?.domain == NSURLErrorDomain && error?.code == NSURLErrorTimedOut)) else {
speedTestCompletionHandler?(nil, error)
return
}
let speed = elapsed != 0 ? Double(bytesReceived)/elapsed/1024.0/1024.0 : -1
speedTestCompletionHandler?(speed, nil)
}
Не могли бы вы любезно рассказать мне, в чем проблема? Я давно застрял. Благодаря!
@Tony Tarng вы проверили код и пробовали? –
Привет, я только что попробовал, и я получаю это сообщение об ошибке:> 2017-02-17 15: 21: 10.242258 Проверка WiFi [29684: 8630707] [] __nw_connection_get_connected_socket_block_invoke 2 Соединение не имеет подключенного обработчика 2017-02- 17 15: 21: 10.287149 Тестирование WiFi [29684: 8630710] [] __nw_connection_get_connected_socket_block_invoke 3 Соединение не имеет подключенного обработчика 2017-02-17 15: 21: 10.289084 Проверка WiFi [29684: 8630729] Сбой PAC с 2017-02-17 15: 21: 10.291110 Тестирование WiFi [29684: 8630710] [] nw_proxy_resolver_create_parsed_array Ошибка оценки PAC: kCFErrorDomainCFNetwork: 2 nil; nil –
Кроме того, если это имеет какое-либо значение, я использую тестовый источник загрузки: https://turnkeyinternet.net/speed-test/1mb.bin –