2017-10-29 22 views
0

현재 다운로드 작업을 사용할 때 사용자 인터페이스의 업데이트에 문제가 있습니다. 다음 함수는 사용자 인터페이스를 업데이트해야하지만 때때로 작동합니다. 파일을 다운로드 할 때마다 왜 작동하지 않습니까? 매번 NSLog의 로그가 디버거에 표시됩니다!urlSession에서 UI 업데이트가 작동하지 않습니다. downloadTask didWriteData

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 
    let curDownloadSize = totalBytesWritten/(1024*1024) 
    let totalDownloadSize = totalBytesExpectedToWrite/(1024*1024) 

    if curDownloadSize != oldDownloadSize { 
    DispatchQueue.main.async { 
     self.progressLabel!.text = "\(self.curDownloadSize)MB/\(self.totalDownloadSize)MB" 
     self.progressView!.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
     NSLog("Download progress: \(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite))"); 
    } 
    } 
} 

progressLabelprogressView이 시간에 모두 사용할 수 있습니다.

나는 같은 파일을 여러 번 시험해 보았지만 때로는 제대로 작동하는지, 때로는 작동하지 않는 경우도 있습니다.

업데이트 : 나는이

DispatchQueue.global(qos: .utility).async { 
    DispatchQueue.main.async { 
    (same as above) 
    } 
} 

같은 두 번째 파견 큐를 사용하는 방법에 대한 읽을 수 있지만이 또한 단지 때때로 노력하고 있습니다.

+0

해당 메소드 내에서 DispatchQueue를 전혀 사용할 필요가 없습니다. –

+0

그래, 전에 DispatchQueue와 같이 작동하지 않는다고 생각하는 것 외에는 같은 결과로 시도해 보았습니다. – who9vy

+0

여러 다운로드를 동시에하고 있습니까? 레이블은 하나뿐입니다. 새 세션을 시작하기 전에 이전 세션 작업을 취소해야합니다. –

답변

0

최근에 나는이 문제를 해결했습니다.

너무 많은 이벤트가 기본 큐로 푸시되는 경우 문제가 발생합니다. 그것은 단지 좋은 인터넷 연결로 발생했습니다. 이 경우 콜백이 너무 자주 호출되었습니다.

내 솔루션 :

progressCounter += 1 
if progressCounter % 30 == 0 { 
    DispatchQueue.main.async { 
    self.progressLabel!.text = "\(self.curDownloadSize)MB/\(self.totalDownloadSize)MB" 
    self.progressView!.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
    NSLog("Download progress: \(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite))"); 
    } 
} 

progressCounter 전에 0으로 초기화되었습니다.