Error (“'()' is not identical to 'UInt8'”) writing NSData bytes to NSOutputStream using the write function in Swift

前端 未结 2 1254
一个人的身影
一个人的身影 2020-12-19 22:46

I\'m trying to build an asynchronous file download in Swift based on the Erica Sadun\'s method. But I need it to handle bigger files, so I found this answer about using a NS

2条回答
  •  甜味超标
    2020-12-19 23:09

    You can cast the pointer with UnsafePointer():

    bytesWritten = self.downloadStream.write(UnsafePointer(data.bytes), maxLength: bytesLeftToWrite)
    

    There is also a problem in your write loop, because you always write the initial bytes of the data object to the output stream.

    It should probably look similar to this (untested):

    var bytes = UnsafePointer(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
    
        // ...
    }
    

提交回复
热议问题