2017-04-02 41 views
1

我需要知道如何在代表的URLsession中捕獲錯誤(主要是中斷)。Swift 3:在URLSession代理中處理錯誤

我有一個自定義類中的下列斯威夫特功能,下載一個小文件來測試下載速度:

func testSpeed() { 

    Globals.shared.dlStartTime = Date() 
    Globals.shared.DownComplete = false 


    let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) 

    let task = session.downloadTask(with: url!) 

    if Globals.shared.currentSSID == "" { 
     Globals.shared.bandwidth = 0 
     Globals.shared.DownComplete = true 

     session.invalidateAndCancel() 

     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) 

    } else { 
     print("Running Task") 
     task.resume() 

    } 
} 

此類使用URLSessionDelegateURLSessionDownloadDelegate。下面是它調用當前代表:

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 
    Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8)/1000 
    let progress = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100.0 
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress]) 
} 

^那一個監控下載進度,並使用通知中心發送進度回視圖控制器。

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { 
    print("Done") 
    if Globals.shared.DownComplete == false { 
     let elapsed = Double(Date().timeIntervalSince(Globals.shared.dlStartTime)) 
     Globals.shared.bandwidth = Int(Globals.shared.dlFileSize/elapsed) 
     Globals.shared.DownComplete = true 
     Globals.shared.dataUse! += (Globals.shared.dlFileSize!/8000) 
    } 
    session.invalidateAndCancel() 

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) 
} 

^那一個纔算一旦下載完成的速度,並將結果發送到一個全局變量在另一個類。不重要。

截至目前,當我測試我的應用程序,中斷下載只是掛的應用程序,因爲它持續等待processFinished NC通話,這顯然永遠不會到來。

是否有另一個代表我應該補充來捕捉這種中斷,還是我錯過了更明顯的東西?

回答

1

您可以使用urlSession:任務:didCompleteWithError委託方法

enter image description here

+0

有趣的是,我已經嘗試過這一點,並沒有奏效。但現在它確實如此。我想這只是Xcode中那些許多事情中的一個,有時會出現問題。 –