gpt4 book ai didi

ios - 添加进度条到下载文件

转载 作者:行者123 更新时间:2023-11-28 14:26:45 25 4
gpt4 key购买 nike

<分区>

我正在实现一个 ViewController 来显示以前从我的服务器下载并存储在设备本地的 PDF,它工作正常,但下载 PDF 需要太多时间,我想实现一个进度条.

我的代码如下,其中我尝试实现 @IBOutlet weak var downloadBar: UIProgressView!因为我得到了下载所需的时间,所以我吃我的代码达到 100%,下载还没有结束。

class PDFViewController: UIViewController {
@IBOutlet weak var pdfView: PDFView!

@IBOutlet weak var downloadBar: UIProgressView!

//*******
var downloader = Timer()
var minValue = 0
var maxValue = 100
//********

var namePDF:String?

override func viewDidLoad() {
super.viewDidLoad()

downloadBar.setProgress(0, animated: false)


if let pdfUrl = URL(string: "https://miserver.com/\(namePDF!).pdf") {


print(pdfUrl)

// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(pdfUrl.lastPathComponent)
print(destinationUrl)

// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")

/************** show pdf ****************/
let pdfUrl = destinationUrl.path
let rutafile = URL(fileURLWithPath: pdfUrl)
print(pdfUrl)
if let document = PDFDocument(url: rutafile) {
pdfView.autoScales = true
pdfView.document = document
}
/************** end show pdf ****************/


// if the file doesn't exist
} else {
print("file doesn't exist")

downloader = Timer.scheduledTimer(timeInterval: 0.06, target: self, selector: (#selector(PDFViewController.updater)), userInfo: nil, repeats: true)
downloadBar.setProgress(0, animated: false)

// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: pdfUrl, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: location, to: destinationUrl)
print("File moved to documents folder")

print("file has already been downloaded")
/************** show pdf ****************/
let pdfUrl = destinationUrl.path
let rutafile = URL(fileURLWithPath: pdfUrl)
print(pdfUrl)
if let document = PDFDocument(url: rutafile) {
self.pdfView.autoScales = true
self.pdfView.document = document
}
/************** show pdf ****************/

} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
}



}

@objc func updater() {

if minValue != maxValue {
minValue += 1
downloadBar.progress = Float(minValue) / Float(maxValue)

print(Float(minValue) / Float(maxValue))
} else {
minValue = 0
downloader.invalidate()
}
}

从已经非常感谢你

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