在Swift中的NSURLSession下载期间未调用URLSession委托

时间:2014-09-01 21:46:37

标签: ios delegates swift nsurlsession

我正在尝试使用委托方法更新进度条,因为使用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];

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

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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

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

.....
}

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