0

Say you are making an iOS app that downloads files from the internet using the code below:

let videoImageUrl = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4"

DispatchQueue.global(qos: .background).async {
    if let url = URL(string: urlString),
        let urlData = NSData(contentsOf: url) {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
        let filePath="\(documentsPath)/tempFile.mp4"
        DispatchQueue.main.async {
            urlData.write(toFile: filePath, atomically: true)
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
            }) { completed, error in
                if completed {
                    print("Video is saved!")
                }
            }
        }
    }
}

Source: Swift - Download a video from distant URL and save it in an photo album

If you call this function twice, you will have two simultaneous connections but only one internet source, so effectively the two threads have to share the same internet bandwidth.

How does the breakdown of which thread gets more bandwidth work? How is this bandwidth allocated?

Jake Chasan
  • 6,290
  • 9
  • 44
  • 90
  • First, you probably want to use `.utility` rather than `.background` - The `.background` qos level can be starved of CPU in some situations. Each of the downloads will take place of a separate TCP connection, even though those connections are between the same endpoints (The iOS device and the server). In theory, each stream gets the same amount of bandwidth, but in practice there are other processes on each end also using the network and there are unknowns in the network elements between the two endpoints. – Paulw11 Mar 25 '19 at 02:34
  • In general, if the two files were the same size you would expect them to complete downloading at approximately the same time. Downloading the two images may not take twice as long as downloading one, however. There may be traffic shaping or other bandwidth management in place that rate limits a given stream. If this rate limit is less than the available bandwidth between the two endpoints then you can add the second stream without impacting the first. – Paulw11 Mar 25 '19 at 02:35

0 Answers0