我试图弄清楚如何使用progressView来显示使用Realm下载的内容的进度。通过阅读,似乎需要找到一个名为progress的Float,但我不知道如何在Realm中找到它。我看过以下问题,但我认为在这种情况下它们没有太大帮助: Swift: Realm - Update UI (Progress) while adding Data to DB iOS-Swift How to update progressView
这是我目前所拥有的: ViewController:
import UIKit
import Realm
import RealmSwift
class ViewController: UIViewController {
var data = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."
var realm: Realm!
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
print("Hello")
print(Realm.Configuration.defaultConfiguration.fileURL!)
realm = try! Realm()
}
@IBAction func saveBtnPressed(_ sender: Any) {
saveToRealm(id: 1, name: "One", data: data)
let progress: Float = 0
progressView.setProgress(progress, animated: true)
}
func saveToRealm(id: Int, name: String, data: String) {
let realmSave = RealmSave()
realmSave.id = id
realmSave.name = name
realmSave.data = data
try? realm!.write {
realm.add(realmSave, update: true)
}
}
}
如果有什么我可以帮助的,请询问。谢谢
答案 0 :(得分:1)
首先:定义一个值为0的let常数将始终为0。您无法动态更改该常数以反映您的下载状态。
正如Realm工程师在this帖子中指出的那样:“ Realm无法知道全部数据。” 估计进度应该在代码中完成。
您可以尝试这样的事情:
func estimateProgress() {
let dataString = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."
let data = dataString.data(using: .utf8)
let count = Float((data?.count)!)
let percentage: Float = count / 100
var progress: Float = 0
if progress < count {
progress += percentage
} else {
progress = count
}
progressView.setProgress(progress, animated: true)
print(progress)
}
请注意,此解决方案用于更新UI并告知用户正在保存到Realm。由于它使用数据中的字节数,因此数据越大,填充进度条所需的时间就越长。因此,这对UI有利,但不是实际的进度状态。
如果您觉得进度条填充得慢/快,您可以随时调整百分比。