Я редактирую из файла загрузки (загрузка нескольких файлов работает нормально.)
загрузка файла из
Как обновить Прогресс в ячейке uitableview по urlsession (скачать / загрузить файл )
, но изменение в файле прогресса просмотра не обновляется в ячейке. ??
import UIKit
class ViewController: UIViewController
{
var url : URL?
var DestFolder : String?
var dataArr : NSMutableArray = NSMutableArray.init()
var dataArrDone : NSMutableArray = NSMutableArray.init()
var myTableview:UITableView = UITableView.init()
let color = UIColor(red: 69/255, green: 57/255, blue: 169/255, alpha: 1.0)
let cellID: String = "customCell"
var downloadTasks: [URLSessionDownloadTask : IndexPath] = [:]
func viewTag(for indexPath: IndexPath) -> Int {
return indexPath.row + 1000
}
override var preferredStatusBarStyle: UIStatusBarStyle {
// Change font of status bar is white.
.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
dataArr=["1.jpg","2.jpg","3.jpg","4.jpg"]
dataArrDone=["wait","wait","wait","wait"]
//print(dataArr)
let myScreen = UIScreen.main.bounds
let statusHieght = UIApplication.shared.statusBarFrame.height
if #available(iOS 13.0, *) {
let app = UIApplication.shared
let statusBarHeight: CGFloat = app.statusBarFrame.size.height
let statusbarView = UIView()
statusbarView.backgroundColor = color
statusbarView.tintColor = .white
view.addSubview(statusbarView)
statusbarView.translatesAutoresizingMaskIntoConstraints = false
statusbarView.heightAnchor
.constraint(equalToConstant: statusBarHeight).isActive = true
statusbarView.widthAnchor
.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
statusbarView.topAnchor
.constraint(equalTo: view.topAnchor).isActive = true
statusbarView.centerXAnchor
.constraint(equalTo: view.centerXAnchor).isActive = true
} else {
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = color
}
UINavigationBar.appearance().barTintColor = color
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
let navBar = UINavigationBar(frame: CGRect(x: 0, y: statusHieght, width: myScreen.size.width, height: 44))
//navBar.isTranslucent=true
//navBar.backgroundColor = .red
let navItem = UINavigationItem(title: "SomeTitle")
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target:nil , action:#selector(ClickDone))
navItem.rightBarButtonItem = doneItem
navBar.setItems([navItem], animated: false)
self.view.addSubview(navBar)
let AllTopDistance=statusHieght+navBar.frame.size.height
let myView:UIView = UIView.init(frame: CGRect(x: 0, y: AllTopDistance, width: myScreen.size.width, height: myScreen.size.height-AllTopDistance))
myView.backgroundColor = .lightGray
myTableview=UITableView.init(frame: CGRect(x: 0, y: 0, width: myScreen.size.width, height: myScreen.size.height-AllTopDistance))
myTableview.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
print("\(statusHieght) \(myScreen.size.width) \(AllTopDistance)")
myTableview.delegate=self
myTableview.dataSource=self
//myTableview.backgroundColor=UIColor.red
myView.addSubview(myTableview)
self.view.addSubview(myView)
}
@objc func ClickDone(){
print("Done")
}
@objc func DownloadFiles(Filename : String , getIndexPath : IndexPath){
url = URL(string: "http://49.xx.xx.xx/TestDownload/\(Filename)")!
DestFolder = "JPG"
print("download \(String(describing: url))")
let config = URLSessionConfiguration.background(withIdentifier: "com.example.DownloadTaskExample.background")
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let downloadsPath = docURL.appendingPathComponent(DestFolder!)
if !FileManager.default.fileExists(atPath: downloadsPath.absoluteString) {
do {
try FileManager.default.createDirectory(atPath: downloadsPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription);
}
}
let prevFile = downloadsPath.appendingPathComponent(url!.lastPathComponent)
if FileManager().fileExists(atPath: prevFile.path) {
debugPrint("The file already exists at path, deleting and replacing with latest \(prevFile.path)")
//print(prevFile)
if FileManager().isDeletableFile(atPath: prevFile.path){
do{
try FileManager().removeItem(atPath: prevFile.path)
debugPrint("previous file deleted \(prevFile.path)")
let task = session.downloadTask(with: url!)
task.resume()
}catch{
debugPrint("current file could not be deleted \(prevFile.path)")
}
}
// download the data from your url
}else{
let task = session.downloadTask(with: url!)
task.resume()
}
}
}
extension ViewController: URLSessionDelegate, URLSessionDownloadDelegate, URLSessionTaskDelegate
{
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite > 0 {
let downloadProgress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("\(downloadProgress)")
print("\(downloadTasks[downloadTask])")
guard let indexPath = downloadTasks[downloadTask] else { return }
let myViewTag = viewTag(for: indexPath)
guard let progressBar = self.view.viewWithTag(myViewTag) as? UIProgressView else { return }
//let tableIndex = NSIndexPath(row: uploadTasks[task]!.row, section: 0)
DispatchQueue.main.async {
progressBar.progress = downloadProgress
if(downloadProgress==1)
{
progressBar.removeFromSuperview()
let indexPosition = IndexPath(row: self.downloadTasks[downloadTask]!.row, section: 0)
self.dataArrDone.replaceObject(at: self.downloadTasks[downloadTask]!.row, with: "Done")
self.myTableview.reloadRows(at: [indexPosition], with: .none)
}
}
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
// your destination file url
let destination = documentsUrl.appendingPathComponent("\(DestFolder!)/\(url!.lastPathComponent)")
let responseStatusCode = (downloadTask.response as! HTTPURLResponse).statusCode
debugPrint("Download finished: \(location) to \(destination) code \(responseStatusCode)")
if(responseStatusCode==200)
{
do{
try FileManager.default.moveItem(at: location, to: destination)
debugPrint("new file saved")
} catch {
debugPrint("file could not be saved")
}
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let hCell:CGFloat = 50.0
return hCell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableview.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
let customKeys=["type","Facebook","Google","Twitter"];
let customsValues=["uploadFile","Mark","Lary","Goo"];
let customDatas=Dictionary(uniqueKeysWithValues: zip(customKeys,customsValues))
//uploadImage(data_dict: customDatas, indexPath : IndexPath)
let Done : NSString = dataArrDone[indexPath.row] as! NSString
if(Done .isEqual(to: "wait"))
{
let progressView = UIView(frame: CGRect(x: 100, y: 10, width: 100, height: 20))
progressView.backgroundColor = UIColor.clear
let progressBar = UIProgressView.init(frame: CGRect(x: 0, y: 5, width: 100, height: 20))
progressBar.tag=viewTag(for: indexPath)
progressBar.backgroundColor = UIColor.green
progressView.addSubview(progressBar)
cell.addSubview(progressView)
DownloadFiles(Filename: dataArr[indexPath.row] as! String, getIndexPath: indexPath)
}else{
//progressView.removeFromSuperview()
let doneText: UILabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
doneText.textColor=UIColor.black
doneText.backgroundColor=UIColor.green
doneText.text="Done"
doneText.font=UIFont.systemFont(ofSize: 14)
cell.addSubview(doneText)
}
return cell
}
}
после запуска приложения все методы работают. но progressview в ячейке uitableview не обновляет прогресс загрузки.
как это исправить.
Спасибо