URLSessionDownloadTask から進行状況を設定しようとすると、unexpectedly found nil while unwrapping an Optional value
エラーが発生します。私が達成しようとしているのは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 でできるだけ多くのプロセスを維持しながら、 の値を適切に設定するにはどうすればよいでしょうか?