尝试从 URLSessionDownloadTask 设置进度时,出现unexpectedly found nil while unwrapping an Optional value
错误。我想要完成的是有一个单独的类 a 来URLSessionDownloadDelegate
处理下载并更新必要的 UI 元素,在这种情况下是一个NSProgressIndicator
. 这是我的代码:
AppDelegate.swift
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet var button: NSButton!
@IBOutlet var progind: NSProgressIndicator!
@IBAction func update(_ sender:AnyObject){
button.isEnabled = false
updater().downloadupdate(arg1: "first argument")
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
progind.doubleValue = 50.0 //me trying to test if the progress indicator even works
}
func applicationWillTerminate(_ aNotification: Notification) {
}
func updateDownload(done: Double, expect: Double){
print(done)
print(expect)
progind.maxValue = expect //this line crashes from the unexpected nil error
progind.doubleValue = done //so does this one, if I delete the one above
}
}
updater.swift
import Foundation
class updater: NSObject, URLSessionDelegate, URLSessionDownloadDelegate {
func downloadupdate(arg1: String){
print(arg1)
let requestURL: URL = URL(string: "https://www.apple.com")!
let urlRequest: URLRequest = URLRequest(url: requestURL as URL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let downloads = session.downloadTask(with: urlRequest)
print("starting download...")
downloads.resume()
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
print("download finished!")
print(location)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let expectDouble = Double(totalBytesExpectedToWrite)
let doneDouble = Double(totalBytesWritten)
AppDelegate().updateDownload(done: doneDouble, expect: expectDouble)
}
}
我试过更换
AppDelegate().updateDownload(done: doneDouble, expect: expectDouble)
和
AppDelegate().progind.maxValue = expect
AppDelegate().progind.doubleValue = done
并得到了相同的结果。
我实际上认为我知道是什么原因造成的。我的研究使我相信我实际上是在声明一个新的实例AppDelegate
,其中progind
甚至不存在!那么如何正确设置 的值progind
,同时在 updater.swift 中保留尽可能多的过程呢?