首页 > 解决方案 > 下载进度应该显示整个应用程序 IOS Swift 吗?

问题描述

我们开始下载的视图控件的初始视图 一旦开始下载,它看起来像这样 我在一个 mp3 应用程序中工作,当用户单击下载按钮时,我需要从显示的列表中下载 mp3,它显示了暂停、停止和进度视图的控件。我的下载正在运行,但我无法显示整个应用程序的下载进度。例如:如果我正在下载一些“x.mp3”歌曲,如果用户在 VC1 中单击 x.mp3,则进度也应显示在 VC3 中。然后我面临的最大问题是下载下载控件后应该隐藏。由于 tableview 重新加载功能,我无法处理 UIrefresh,它应该显示下载控件以及相应的下载按钮。我已将我的 ViewController 类附加到单元类以及我已附加“CELLFORROWATINDEXPATH”的设计

视图控制器 Cellforrowatindexpath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let table_cell = tableView.dequeueReusableCell(withIdentifier: "LecturesVcCellID", for: indexPath) as! LecturesVcCell

    let trackdata = searchResults[indexPath.row]

   constantsList.playTypeArray.boolArray.append(false)

    table_cell.configure(track: trackdata, index: indexPath.row)

    table_cell.downloadbtn.tag = indexPath.row

    table_cell.pauseButton.tag = indexPath.row

    table_cell.cancelButton.tag = indexPath.row

    table_cell.progressLabel.tag = indexPath.row

    let x : Int = trackdata.classNumber as! Int
    let className = String(x)

    if index == indexPath.row {
        table_cell.img_play.image=#imageLiteral(resourceName: "playing_track")
        table_cell.lbl_SubTitle.text = "Now playing"
        table_cell.lbl_SubTitle.textColor = #colorLiteral(red: 0.968627451, green: 0.7490196078, blue: 0.4823529412, alpha: 1)
    }else {
        table_cell.img_play.image=#imageLiteral(resourceName: "play_track")
        table_cell.lbl_SubTitle.text = String(format: "Class - %@ | %@",  className,(trackdata.timeoftrack!))
        table_cell.lbl_SubTitle.textColor = UIColor.lightGray
    }

    str_image = "https://www.imaginetventures.name/swamiji/wp-content/uploads/2019/01/introved.png"
    constantsList.playTypeArray.imageLecture = str_image
    table_cell.img_Show.sd_setImage(with: URL(string: str_image), placeholderImage: UIImage(named: "placeholder.png"))

    table_cell.navigationController = self.navigationController

    if str_Type .isEqual(to: "Playlist") {
        table_cell.downloadbtn.isHidden = true
     //   table_cell.playlistAdditionImageview.isHidden = false

        if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
            table_cell.playlistAdditionImageview.isHidden = true
        }else {
            table_cell.playlistAdditionImageview.isHidden = false
        }


    }else {

        table_cell.downloadbtn.setImage(UIImage(named: "DATA11"), for: .normal)
     //   table_cell.playlistAdditionImageview.isHidden = true
    }

    table_cell.selectionStyle = .none
    return table_cell
}

viewcontrollercell 类文件:

override func awakeFromNib() {
    super.awakeFromNib()

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    context = appDelegate.persistentContainer.viewContext
    entity = NSEntityDescription.entity(forEntityName: "DownloadList", in: context)

}

@IBAction func pauseBtnAction (_ sender: UIButton) {
    if(downloadTask != nil && isDownload) {
        downloadTask!.cancel(byProducingResumeData: { (resumeData) -> Void in
            self.downloadData = resumeData
        })
        isDownload = false
        downloadTask = nil
        pauseButton.setImage(UIImage(named: "start-button"), for: .normal)
    }else
        if(!isDownload && downloadData != nil) {
            if let resumeData =  self.downloadData {
                downloadTask = urlSession?.downloadTask(withResumeData: resumeData)
            } else {
                let url:URL = URL(string: "\((constantsList.playTypeArray.arr_subCatagriesLecture.object(at: sender.tag) as AnyObject).value(forKey: "mp3") as! String)")!
                downloadTask = downloadsSession?.downloadTask(with: url)
            }
            downloadTask!.resume()
            isDownload = true
            pauseButton.setImage(UIImage(named: "x"), for: .normal)
    }
}

@IBAction func cancelBtnClicked (_ sender: UIButton) {
    downloadTask?.cancel()
    downloadData = nil
    isDownload = false
    downloadTask = nil
    progress.progress = 0
    progressLabel.text = "0%"
    progress.setProgress(0.0, animated: true)
    cancelButton.isHidden = true
    pauseButton.isHidden = true
    downloadbtn.isHidden = false
    progressLabel.isHidden = true
    progress.isHidden = true
}
    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    DispatchQueue.main.async {
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate,
            let completionHandler = appDelegate.backgroundSessionCompletionHandler {
            appDelegate.backgroundSessionCompletionHandler = nil
            completionHandler()
        }
    }
}
    @IBAction func downloadBtnAction(_ sender: UIButton) {

   // sender.pulse()
    self.reachability = Reachability.init()
    if ((self.reachability?.connection) != .none) {
        switch self.reachability?.connection {
        case .wifi?:
            print("Wifi")
            print(sender.tag)
            constantsList.playTypeArray.typeofnetwork = true
            downloadTapped(sender: sender.tag)
        case .cellular?:
            print("mobile data")
            print(sender.tag)
            let alert = UIAlertController(title: "Mobile Data usage Alert!", message: "Downloads will be using mobile data!!", preferredStyle: UIAlertController.Style.alert);
            let action1 = UIAlertAction(title: "Ok", style: .default) { (action:UIAlertAction) in
                self.downloadTapped(sender: sender.tag)
            }
            let action2 = UIAlertAction(title: "Cancel", style: .default) { (action:UIAlertAction) in
                print("Cancelled")
            }
            alert.addAction(action1)
            alert.addAction(action2)
            self.navigationController?.present(alert, animated: true, completion: nil)
        case .none:
            print("Network Not reachable")
        case .some(.none):
            print("Some")
        }
    }else {
        print("No Internet")
    }
}

func downloadTapped(sender : Int) {
    constantsList.playTypeArray.arrayDownloadSort.append(sender as NSNumber)
    print(constantsList.playTypeArray.arrayDownloadSort)
    constantsList.playTypeArray.boolArray[sender] = true
    showDownloadControls = true
    downloadbtn.isHidden = true
    pauseButton.isHidden = false
    cancelButton.isHidden = false
    progressLabel.isHidden = true
    progress.isHidden = false
    progressLabel.text = "Downloading..."

    var urlConfiguration:URLSessionConfiguration!
    urlConfiguration = URLSessionConfiguration.default
    let queue:OperationQueue = OperationQueue.main
    urlSession = URLSession.init(configuration: urlConfiguration, delegate: self, delegateQueue: queue)
    let url:NSURL = NSURL(string: "\((constantsList.playTypeArray.arr_subCatagriesLecture.object(at: sender) as AnyObject).value(forKey: "mp3") as! String)")!
    downloadTask = urlSession.downloadTask(with: url as URL)
    downloadTask.resume()
}


//DOWNLOADING THE FILE UPDATE THE PROGRESS

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    //    2
    let progress1 = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite);
    //     3
    print(progress1)
    //       4
  //  OperationQueue.main.addOperation

    DispatchQueue.main.async (execute: {

        self.isDownload = true
        //     2
        constantsList.playTypeArray.isDownloading = true
        self.progress.setProgress(progress1, animated: false)

        self.progressLabel.text = String(progress1 * 100) + "%"

        constantsList.playTypeArray.setprogress = progress1

        let i = 0

        if progress1 == 1.0 {

            constantsList.playTypeArray.isDownloading = false
            print(i + 1)
        }

    })
}

//AFTER DOWNLOADING SAVE THE FILE TO APP DATA
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("Finish Downloading")
    let filemanager = FileManager()
    let directoryURL = filemanager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    print(directoryURL)
    let docDirectoryURL = NSURL(fileURLWithPath: "\(directoryURL)")
    print(docDirectoryURL)
    let destinationFileName = downloadTask.originalRequest?.url?.lastPathComponent
    print(destinationFileName!)
    let destinationURL = docDirectoryURL.appendingPathComponent("\(destinationFileName!)")
    print(destinationURL!)
    if let path = destinationURL?.path {
        if filemanager.fileExists(atPath: path) {
            do {
                try filemanager.removeItem(at: destinationURL!)
            }catch let error as NSError{
                print(error.localizedDescription)
            }
        }
    }
    do {
        try filemanager.copyItem(at: location, to: destinationURL!)
        print(destinationURL!)
        print(downloadbtn.tag)
        newUser = NSManagedObject(entity: entity!, insertInto: context)
        dic66 = constantsList.playTypeArray.arr_subCatagriesLecture.object(at:  downloadbtn.tag) as? NSDictionary
        newUser.setValue(dic66?.value(forKey: "classname") as! NSNumber, forKey: "classname")
        newUser.setValue("\(String(describing: dic66?.value(forKey: "time") as! String))", forKey: "time")
        newUser.setValue("\(String(describing: dic66?.value(forKey: "title") as! String))", forKey: "songtitle")
        newUser.setValue("\(destinationURL!.path)", forKey: "mp3Url")
        newUser.setValue("\(String(describing:  constantsList.playTypeArray.imageLecture!))", forKey: "imageurl")
        do {
            try context.save()
            print(context)
            self.cancelButton.isHidden = true
            self.pauseButton.isHidden = true
            self.downloadbtn.isHidden = true
            self.progressLabel.isHidden = true
            self.progress.isHidden = true
            print("Successful")
        } catch {
            print("failed")
        }
    }catch {
        print("Error while copying file")
    }
    downloadData = nil;
}

func configure(track: Track,index: Int) {
     var filefound: Bool = false
    var shopwControls: Bool = true

    if(constantsList.playTypeArray.boolArray[index]) {
         filefound = true
         shopwControls = false
        self.progress.setProgress(constantsList.playTypeArray.setprogress, animated: true)
    }

    lbl_Title.text = track.songTitle

    //CLASS AND VOLUME UPDATION
    let x : Int = track.classNumber as! Int
    let className = String(x)
    lbl_SubTitle.text = String(format: "Class - %@ | %@", className,(track.timeoftrack!))

    //core Data checking for already downloaded file
    request.returnsObjectsAsFaults = false
    request.resultType = .dictionaryResultType
    do {
        let result = try context.fetch(request)
        dic66 = constantsList.playTypeArray.arr_subCatagriesLecture.object(at:  index) as? NSDictionary
        for data in result as! [[String:Any]] {
            print(data["classname"] as! Int)
            print(dic66?.value(forKey: "classname") as! Int)
            if data["classname"] as! Int == (dic66?.value(forKey: "classname") as! Int)  {
                filefound = true
            }
        }
    } catch {
        print("Failed")
    }

    //       If the track is already downloaded, enable cell selection and hide the Download button
    selectionStyle = filefound ? UITableViewCell.SelectionStyle.gray : UITableViewCell.SelectionStyle.none
    downloadbtn.isHidden = filefound
    pauseButton.isHidden = shopwControls
    cancelButton.isHidden = shopwControls
    progress.isHidden = shopwControls
}

}

标签: iosswiftdownload

解决方案


推荐阅读