【发布时间】:2014-09-01 21:46:36
【问题描述】:
当使用NSURLSession 下载文件时,我正在尝试使用委托方法更新进度条,但我似乎无法调用委托方法。
我在 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];
[.............]
}];
}
}
我感觉到我做错了,尽管在这两种情况下,我都没有在 ObjectiveC 中使用我需要访问的变量(例如didWriteData、bytesWritten 等)填充自动填充,在我输入-(void)URLSession:(NSURLSession *)session 后,我会得到downloadTask 和didWriteData 等选项。但是,使用 Swift 我没有得到这些,所以我认为我做错了什么。
提前感谢您的帮助。
【问题讨论】:
标签: ios delegates swift nsurlsession