我必须从API读取文件,但其大小约为1.6 MB,需要很长时间。如何以21个字节的部分读取它?
收到的数据:ScreenShot
我有这个代码,它读取所有文件:
func getLogBinData() {
if let url = URL(string: httpString + "log.bin") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
print()
}
})
task.resume()
}
}
我尝试了下一个代码,但委托方法不起作用。为什么呢?
我添加了按钮,它在控制台task.countOfBytesReceived中打印,并且运行良好
代码:
class ViewController: UIViewController, URLSessionTaskDelegate, URLSessionDelegate, URLSessionDataDelegate {
var task = URLSessionDataTask()
var httpString = "here ip dress of my API"
override func viewDidLoad() {
super.viewDidLoad()
getLogBinData()
}
func getLogBinData() {
if let url = URL(string: httpString + "log.bin") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if dataTask.countOfBytesReceived >= 20 {
print(dataTask.countOfBytesReceived)
}
}
}
答案 0 :(得分:1)
您需要使用URLSession委托方法来监控下载/请求的接收进度。
这些协议包含func urlSession(URLSession, dataTask: URLSessionDataTask, didReceive: Data)等方法,它们会在收到数据块时将其传递给您。
您需要跟踪已接收和解析的数据量,一旦获得新数据> = 21个字节,您可以将其附加到数据并读取下一个数据包。