0

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

そして同じ結果が得られました。

私は実際にこれを引き起こしているものを知っていると思います。私の調査により、実際には の新しいインスタンスを宣言していると信じるに至りましAppDelegateprogindprogindでは、 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 に答える