0

尝试从 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 中保留尽可能多的过程呢?

4

1 回答 1

0

没错,当您键入 时AppDelegate(),您正在创建一个新对象。由于它是新的,它没有像来自故事板或 xib 时那样为它初始化任何出口。

您需要获取代表您的应用程序的共享单例(请参阅NSApplication文档),向它询问其委托,将其转换为AppDelegate,并在那里设置属性。

示例代码(Swift 2.2):

if let delegate = NSApplication.sharedApplication().delegate as? AppDelegate {
    delegate.progind.maxValue = expected
} else {
    print("Unexpected delegate type: \(NSApplication.sharedApplication().delegate)")
}
于 2016-08-25T00:43:42.013 回答