我正在尝试基于Erica Sadun的方法在Swift中构建异步文件下载。但是我需要它来处理更大的文件,因此我找到了有关使用NSOutputStream而不是NSData的答案,这是有意义的。
但是,我无法使其正常工作。当我尝试将NSData字节(在我的NSURLConnection didReceiveData函数中)添加到NSOutputStream写入函数时,出现以下错误:'()' is not identical to 'UInt8'在该行:bytesWritten = self.downloadStream.write(data.bytes, maxLength: bytesLeftToWrite)。
'()' is not identical to 'UInt8'
bytesWritten = self.downloadStream.write(data.bytes, maxLength: bytesLeftToWrite)
data.bytes是类型ConstUnsafePointer<()>,.write()函数期望类型是ConstUnsafePointer<UInt8>,因此从这个意义上说,错误是完全合理的。但是由于我是iOS的新手,当然还不熟悉Swift编程,所以我不了解如何解决此问题。
data.bytes
ConstUnsafePointer<()>
.write()
ConstUnsafePointer<UInt8>
因此,如何将转换data.bytes: ConstUnsafePointer<()>为ConstUnsafePointer<UInt8>alt。以其他方式进行这项工作?
data.bytes: ConstUnsafePointer<()>
我的didReceiveData功能:
didReceiveData
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { var bytesLeftToWrite: NSInteger = data.length var bytesWritten: NSInteger = 0 while bytesLeftToWrite > 0 { bytesWritten = self.downloadStream.write(data.bytes, maxLength: bytesLeftToWrite) if bytesWritten == -1 { break } bytesLeftToWrite -= bytesWritten let responseExpectedlenght: NSNumber = NSNumber(longLong: self.downloadResponse!.expectedContentLength) let dataLength: NSNumber = NSNumber(long: data.length) self.downloadProgressPercentage = ((dataLength / responseExpectedlenght) * 100) println("Downloaded: \(self.downloadProgressPercentage)%") } }
您可以使用以下方法转换指针UnsafePointer():
UnsafePointer()
bytesWritten = self.downloadStream.write(UnsafePointer(data.bytes), maxLength: bytesLeftToWrite)
在写循环中还有一个问题,因为您总是将数据对象的 初始 字节写入 输出流。
它可能看起来与此类似(未试用):
var bytes = UnsafePointer<UInt8>(data.bytes) var bytesLeftToWrite: NSInteger = data.length while bytesLeftToWrite > 0 { let bytesWritten = self.downloadStream.write(bytes, maxLength: bytesLeftToWrite) if bytesWritten == -1 { break // Some error occurred ... } bytesLeftToWrite -= bytesWritten bytes += bytesWritten // advance pointer // ... }