假设您正在制作一个iOS应用,可以使用以下代码从互联网下载文件:
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!")
}
}
}
}
}
来源:Swift - Download a video from distant URL and save it in an photo album
如果两次调用此函数,则将同时具有两个连接,但只有一个Internet资源,因此有效地,两个线程必须共享相同的Internet带宽。
哪个线程的故障如何获得更多带宽?如何分配带宽?