【问题标题】:URLSession delegate not called during NSURLSession download in Swift在 Swift 中下载 NSURLSession 期间未调用 URLSession 委托
【发布时间】: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 中使用我需要访问的变量(例如didWriteDatabytesWritten 等)填充自动填充,在我输入-(void)URLSession:(NSURLSession *)session 后,我会得到downloadTaskdidWriteData 等选项。但是,使用 Swift 我没有得到这些,所以我认为我做错了什么。

提前感谢您的帮助。

【问题讨论】:

    标签: ios delegates swift nsurlsession


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多