在Swift中一次下载多个文件

时间:2015-03-09 23:51:55

标签: swift nsurlconnection nsurlrequest

我终于可以使用以下代码从服务器下载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,你能帮我学习正确的多个文件下载形式吗? / p>

非常感谢你!

1 个答案:

答案 0 :(得分:1)

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

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?