I have to read the file from API, but its size is about 1.6 MB, and it takes a long time. How can I read it by parts of 21 bytes?
Received data: ScreenShot
I have this code, which read all file:
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()
}
}
I tried next code, but delegate method don't work. Why?
I adding button, which print in console task.countOfBytesReceived, and it works well
code:
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)
}
}
}
You would need to use the URLSession delegate methods to monitor the receive progress of the download/request.
These protocols contain methods like func urlSession(URLSession, dataTask: URLSessionDataTask, didReceive: Data) which will pass you the received data chunks as they come in.
You will need to keep track of how much data you have received and parsed, once you have a new amount of data >= 21 bytes you can append it to your data and read the next packet.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.