【发布时间】:2015-05-15 14:20:35
【问题描述】:
我正在尝试在一个网站上下载 5MB 大小的 .txt 文件
我尝试直接下载文件,它给出了正确的大小
我尝试通过 Android DownloadManager.Request 下载,它也提供了正确的大小
除了,在 iOS 中,当我尝试通过 NSURLConnection 下载它时, 没有 1 秒,它显示 5MB 大小的成功下载 但是,当我签入接收它的网络时,我只使用了 25kb?
PS。如果我更改为使用 .zip 文件下载相同的域,它会正确下载
问题链接:http://www.bluewindsolution.com/speed_test/downloads/download_file.txt
工作链接: http://www.bluewindsolution.com/speed_test/downloads/download_file.zip
这里是代码
@IBAction func buttonClick(sender: AnyObject) {
let timestamp = NSString(format: "%.0f", NSDate().timeIntervalSince1970)
let url:NSURL = NSURL(string: "http://www.bluewindsolution.com/speed_test/downloads/download_file.txt?time=\(timestamp)")!
var request:NSURLRequest = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
startDate = NSDate()
NSURLConnection(request: request, delegate: self)
}
func connectionDidFinishDownloading(connection: NSURLConnection, destinationURL: NSURL) {
println("finishdownload \(destinationURL)")
println("timetotal: \(timetotal)")
println("speed: \(speed) mbps")
println("filesize: \(filesize)") // it's show 5MB but network just receive only 25KBps ? it's also not the cache because it's happen at the first time also.
connection.cancel()
}
func connection(connection: NSURLConnection, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, expectedTotalBytes: Int64) {
let currentDate:NSDate = NSDate()
let tt = currentDate.timeIntervalSinceDate(startDate)
timetotal = tt // to get total time
speed = Double(totalBytesWritten)/1024/1024*8/tt // to get speed MBps
filesize = Double(totalBytesWritten)/1024/1024 // to get as MB
// use this to get result as real time
//println("timetotal: \(totaltime)")
//println("speed: \() mbps")
//println("filesize: \()")
}
输出结果
模拟器网络接收结果
【问题讨论】:
-
您是在抱怨文件不全还是没有使用足够的数据? NSURLConnection 自动支持 gzip。服务端有压缩吗?此外,操作系统提供缓存。它被缓存了吗?服务器是否返回 304 Not Modified? Wireshark 无所不知。
标签: ios swift nsurlconnection nsurl