如何修改代码以便可以下载多个文件

时间:2016-11-29 09:07:35

标签: swift3 nsurlsession

请问我如何在swift 3中同时制作多个下载文件 我只能下载一个文件,但我怎么能做多个下载文件,我可以控制每个文件,如表视图单元格中的暂停,恢复和进度视图

以下代码下载一个文件:

fun loadMp3() {
        let videoMp3 = "http://www.example.com"
        let url = URL(string: videoMp3)
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let request = NSMutableURLRequest(url: url!)
        request.httpMethod = "GET"
        let task = session.dataTask(with: url!, completionHandler: {
            (data,response,error) in
            if error == nil {

                if let response = response as? HTTPURLResponse {
                    if response.statusCode == 200 {

                        if data != nil {

                            do {
                                let responseOfJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                                let getLink = responseOfJson?["link"] as! String

                                let getVideo = URL(string: getLink)
                                print("Downloading...")
                                DispatchQueue.global(qos: .background).async {
                                    DispatchQueue.main.async {

                                        let getData = try! Data(contentsOf: getVideo!)
                                        self.progressBar.setProgress(Float(getData.count), animated: true)
                                        let fileManager = FileManager.default
                                        let document = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                                        let file = document.appendingPathComponent("WadaetAlhussien.mp3")

                                        try! getData.write(to: file)

                                        print(file)



                                    }
                                }

                            }catch {
                                print(error)
                            }



                        }

                    }
                }


            }

        })
        task.resume()

    }

感谢所有

0 个答案:

没有答案