无法在 Swift 中创建 URLSession 实例
Unable to create an instance of URLSession in Swift
我想看看下载需要多长时间,我看到了这个link on how to do it
,所以我稍微调整了一下(例如更改重命名 类 等)以在 Swift 3 中工作。但是,我有一个问题:let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
我无法修复,并且此错误消息不断弹出:
Argument labels '(configuration:, delegate:, delegateQueue:)' do not match any available overloads
这是我的代码:(有问题的行是以下一行 // ISSUE ON NEXT LINE)
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)
}
}
谁能告诉我这里有什么问题吗?我已经被困了很长一段时间了。谢谢!
检查下面更正后的代码
import UIKit
/* check delegate changes */
class ViewController: UIViewController, URLSessionTaskDelegate {
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 = URL(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 IS NOW RESOLVED///////////////////
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
session.dataTask(with: url).resume()
}
/* changes is below */
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
bytesReceived! += data.count
stopTime = CFAbsoluteTimeGetCurrent()
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let elapsed = stopTime - startTime
guard let nserror = error as? NSError, elapsed != 0 && (nserror.domain == NSURLErrorDomain && nserror.code == NSURLErrorTimedOut) else {
speedTestCompletionHandler?(nil, error as? NSError)
return
}
let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
speedTestCompletionHandler?(speed, nil)
}
/* changes end */
}
我想看看下载需要多长时间,我看到了这个link on how to do it
,所以我稍微调整了一下(例如更改重命名 类 等)以在 Swift 3 中工作。但是,我有一个问题:let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
我无法修复,并且此错误消息不断弹出:
Argument labels '(configuration:, delegate:, delegateQueue:)' do not match any available overloads
这是我的代码:(有问题的行是以下一行 // ISSUE ON NEXT LINE)
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)
}
}
谁能告诉我这里有什么问题吗?我已经被困了很长一段时间了。谢谢!
检查下面更正后的代码
import UIKit
/* check delegate changes */
class ViewController: UIViewController, URLSessionTaskDelegate {
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 = URL(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 IS NOW RESOLVED///////////////////
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
session.dataTask(with: url).resume()
}
/* changes is below */
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
bytesReceived! += data.count
stopTime = CFAbsoluteTimeGetCurrent()
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let elapsed = stopTime - startTime
guard let nserror = error as? NSError, elapsed != 0 && (nserror.domain == NSURLErrorDomain && nserror.code == NSURLErrorTimedOut) else {
speedTestCompletionHandler?(nil, error as? NSError)
return
}
let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
speedTestCompletionHandler?(speed, nil)
}
/* changes end */
}