[英]how to pass properties to swift 3 urlsession didFinishDownloadingTo delegate after background download?
[英]URLSession delegate not called during NSURLSession download in Swift
我正在尝试使用委托方法来更新进度条,因为使用NSURLSession
下载文件时,但是似乎无法调用Delegate方法。
在Swift中,我拥有的委托方法如下(启动文件下载时不会调用):
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64!, totalBytesExpectedToWrite: Int64){
println("delegate called")
if (totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown) {
println("Unknown transfer size")
} else {
let index: Int = self.getFileDownloadInfoIndexWithTaskIdentifier(downloadTask.taskIdentifier)
let fdi: FileDownloadInfo = self.arrFileDownloadData.objectAtIndex(index) as FileDownloadInfo
NSOperationQueue().addOperationWithBlock({
//Calculate the progress
fdi.downloadProgress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
// Update the progressview bar
self.progressView.progress = Float(fdi.downloadProgress)
})
}
}
我试图在上面的Swift中复制的等效Objective-C调用是(启动文件下载时会调用该调用):
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"Delegate called");
if (totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown) {
NSLog(@"Unknown transfer size");
}
else{
// Locate the FileDownloadInfo object among all based on the taskIdentifier property of the task.
int index = [self getFileDownloadInfoIndexWithTaskIdentifier:downloadTask.taskIdentifier];
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:index];
[.............]
}];
}
}
我感觉到我做错了,尽管在这两种情况下,我在键入-(void)URLSession:(NSURLSession *)session
)后都没有在ObjectiveC中自动填充需要访问的变量(例如didWriteData
, bytesWritten
等) -(void)URLSession:(NSURLSession *)session
,我可以选择downloadTask
和didWriteData
等。 但是,使用Swift我没有得到这些,所以我想我做错了。
在此先感谢您的帮助。
我发现了-参数不正确(totalBytesWritten:Int64!末尾不应带有!)。 正确的代码如下:
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
.....
}
另外,建议将NSURLSessionDownloadDelegate分配给包含的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.