1

I am coding iOS app with Swift 5+ . I need to download a file from http url and read it line by line. The file can be big. I do not want to save it locally to temp place to read later. Also, i do not want to load full file to memory.

I found there is support of URLSession with delegate functions. Here i can receive portions of a file data during download. But also this approach returns full contents of the file in the end of the process.

I am using the approach described here https://developer.apple.com/documentation/foundation/url_loading_system/fetching_website_data_into_memory

I have 2 problems:

  1. Full file is still returned in response argument of the task callback
  2. How to make lines from Data() type? bytes are appended to the receivedData variable. How to get string lines from it? How to read bytes till "\n" and convert them to a string?
Roman Gelembjuk
  • 1,797
  • 2
  • 25
  • 50
  • See [my answer here](https://stackoverflow.com/a/67920531/5133585). That answer was about reading from a local file, but it is equally applicable to remote files. It doesn't matter whether it's http:// or file://. – Sweeper Dec 23 '21 at 11:00
  • If you are supporting OS versions prior to iOS 15 or macOS 12, you can’t use that answer. Prior to these OS versions, you have to use traditional patterns. You said “URLSession with delegate functions … But also this approach returns full contents of the file in the end of the process.” No, it doesn’t. The [`urlSession(_:dataTask:didReceive:)`](https://developer.apple.com/documentation/foundation/urlsessiondatadelegate/1411528-urlsession) will be called with chunks of bytes as they come in, and you can parse your strings of text as you go along, not saving the whole thing in `Data` or file. – Rob Dec 23 '21 at 16:08

0 Answers0