gpt4 book ai didi

ios - 在 Swift 中下载 NSURLSession 期间未调用 URLSession 委托(delegate)

转载 作者:搜寻专家 更新时间:2023-11-01 05:43:05 25 4
gpt4 key购买 nike

我正在尝试使用委托(delegate)方法在使用 NSURLSession 下载文件时更新进度条,但是我似乎无法调用委托(delegate)方法。

我在 Swift 中的委托(delegate)方法如下(启动文件下载时不会调用):

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];

[.............]
}];
}
}

我感觉到我做错了什么,尽管在这两种情况下,我都没有用我需要访问的变量填充自动填充(例如 didWriteData bytesWritten 等),在 ObjectiveC 中,在我输入 -(void)URLSession:(NSURLSession *)session 后,我得到了 downloadTaskdidWriteData 等选项。但是,对于 Swift,我没有得到这些,所以我认为我做错了什么。

在此先感谢您的帮助。

最佳答案

我找到了 - 参数不正确(totalBytesWritten:Int64!结尾不应该有 !)。正确代码如下:

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){

.....
}

此外,建议将 NSURLSessionDownloadDelegate 分配给包含类。

关于ios - 在 Swift 中下载 NSURLSession 期间未调用 URLSession 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25613250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com