【发布时间】:2015-11-24 07:30:21
【问题描述】:
我正在遵循以下代码,该代码是从堆栈溢出问题中复制和转换的。
我正在获得互联网速度,但我不确定,如果我做对了。
import UIKit
class ViewController: UIViewController, NSURLConnectionDataDelegate{
var connection:NSURLConnection!
var length:Int!
var startTime:NSDate!
//let kMinimumMegabytesPerSecond: CGFloat = 1
let kMaximumElapsedTime: CGFloat = 2.0
override func viewDidLoad() {
super.viewDidLoad()
self.testDownloadSpeed()
// Do any additional setup after loading the view, typically from a nib.
}
func testDownloadSpeed() {
var url: NSURL = NSURL(string: "http://thewallpaperhost.com/wp-content/uploads/2014/12/wallpapers-hd-8000-8331-hd-wallpapers.jpg")!
var request: NSURLRequest = NSURLRequest(URL: url)
self.startTime = NSDate()
self.length = 0
self.connection = NSURLConnection(request: request, delegate: self)
self.connection.start()
let delayInSeconds:Int64 = 1000000000 * 2
var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, (Int64)(delayInSeconds ))
dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
if let conn = self.connection {
self.connection.cancel()
self.connection = nil
self.useOffline()
}
})
}
func determineMegabytesPerSecond() -> CGFloat {
var elapsed: NSTimeInterval
if (startTime != nil) {
elapsed = NSDate().timeIntervalSinceDate(startTime)
var d = (Double(length) / elapsed)
var result = CGFloat( d/1024)
result = result * 0.0078125
result = result * 0.0009765625
return result
}
return -1
}
func useOnline() {
NSLog("Successful")
NSLog("\(determineMegabytesPerSecond())")
}
func useOffline() {
NSLog("UnSuccessful")
NSLog("\(determineMegabytesPerSecond())")
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
NSLog("data came")
self.startTime = NSDate()
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
if let conn = self.connection {
self.connection = nil
useOffline()
}
}
func connectionDidFinishLoading(connection: NSURLConnection) {
self.connection = nil
useOnline()
}
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.length = self.length + data.length
NSLog("\(data.length)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我从下面的 URL 复制了代码。它在 Objective C 中,所以我转换了代码!
【问题讨论】:
-
嗯...复制不理解?您首先要了解计算网速的逻辑。
-
我理解了逻辑......没有它我怎么能在swift中转换和更改代码!!!LOL
-
我的问题是在确定MegabytesPerSecond() 方法中转换数据,我认为我以哪种形式获取数据?在目标 c 示例中,它将长度除以经过的时间,然后除以 1024 以获得 mb/sec 但我没有得到它
标签: ios swift networking ios8