gpt4 book ai didi

swift - 在 Swift 中一次下载多个文件

转载 作者:行者123 更新时间:2023-11-30 10:18:14 26 4
gpt4 key购买 nike

我终于能够使用以下代码从服务器下载 1 个视频:

    import UIKit

class ViewController: UIViewController, NSURLConnectionDelegate {


var file:NSFileHandle?

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
super.viewDidLoad()
downloadVideo()
}





func downloadVideo(sender: UIButton) {

let urlPath: String = "http://www.ebookfrenzy.com/ios_book/movie/movie.mov"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()

}


func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {


var fileName = "test.mov"

var fileAtPath = fileInDocumentsDirectory(fileName)
if(NSFileManager.defaultManager().fileExistsAtPath(fileAtPath) == false)
{
NSFileManager.defaultManager().createFileAtPath(fileAtPath, contents: nil, attributes: nil)
}

file = NSFileHandle(forWritingAtPath: fileAtPath)!

if ((file) != nil){
file!.seekToEndOfFile()
}


}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){

//write,each,data,received
if(data != nil){


if((file) != nil){

file!.seekToEndOfFile()

}

file!.writeData(data)


}


}

func connectionDidFinishLoading(connection: NSURLConnection!) {

file!.closeFile()
}



func documentsDirectory() -> String {

let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String

return documentsFolderPath
}


func fileInDocumentsDirectory(filename: String) -> String{
return documentsDirectory().stringByAppendingPathComponent(filename)
}



override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

但是我需要下载很多视频文件(我至少有100个URL),我该怎么办?我想一次做一个,但我想在这种方法中我将有很多 NSURLConnections 实例,也许我会吃掉我所有的 RAM,你能帮助我学习多个文件下载的正确形式吗?

非常感谢!

最佳答案

您可以使用并发队列来限制一次最大连接数。

func downloadVideo(sender: UIButton) {
for urlPath in urlPaths {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
}
}
}

如果您想自定义最大连接数,请检查此处: Can I limit concurrent requests using GCD?

关于swift - 在 Swift 中一次下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28953842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com