Handling a pointer with RubyMotion

I am trying to port the following method to RubyMotion

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSInteger dataLength = [data length]; const uint8_t * dataBytes = [data bytes]; NSInteger bytesWritten; NSInteger bytesWrittenSoFar; bytesWrittenSoFar = 0; do { bytesWritten = [self.downloadStream write:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar]; assert(bytesWritten != 0); if (bytesWritten == -1) { [self cleanupConnectionSuccessful:NO]; break; } else { bytesWrittenSoFar += bytesWritten; } } while (bytesWrittenSoFar != dataLength); self.progressContentLength += dataLength; } 

(this is from robertmryan / download-manager )

This is what I currently have that crashes when calling downloadStream using connection:didReceiveData:': can't convert Fixnum into String (TypeError)

 def connection(connection, didReceiveData:data) dataLength = data.length dataBytes = data.bytes bytesWritten = 0 bytesWrittenSoFar = 0 begin maxLength = dataLength - bytesWrittenSoFar buffer = dataBytes[bytesWrittenSoFar] bytesWritten = self.downloadStream.write buffer, maxLength: maxLength # CRASH if bytesWritten == -1 self.cleanupConnectionSuccessful false break else bytesWrittenSoFar += bytesWritten end end while bytesWrittenSoFar != dataLength self.progressContentLength += dataLength if self.delegate.respondsToSelector('downloadDidReceiveData:') self.delegate.downloadDidReceiveData(self) end end 

I understand that my conversion ignores pointers, probably naively and incorrectly. I checked the RubyMotion docs, but they are a little rare, and my understanding of C is not strong enough to know how to apply it here. Some tips would be greatly appreciated.

+4
source share
1 answer

The bytes NSData method returns a Pointer type ( http://www.rubymotion.com/developer-center/api/Pointer.html ).

The [] method in the Pointer type gives you access to the element at this position from the beginning of the pointer. It seems to me that bytes returns a Pointer type "C" (no char sign), so when you try to access the Pointer as dataBytes[bytesWrittenSoFar] , you only get Fixnum , which was the value of this byte from the beginning of the pointer.

To do what you want to do, you will need the following:

 bytesWrittenSoFar = 0 begin maxLength = dataLength - bytesWrittenSoFar buffer = dataBytes + bytesWrittenSoFar bytesWritten = self.downloadStream.write buffer, maxLength: maxLength if bytesWritten == -1 self.cleanupConnectionSuccessful false break else bytesWrittenSoFar += bytesWritten end end while bytesWrittenSoFar != dataLength 

I can’t start it, but I hope it works.

+4
source

Source: https://habr.com/ru/post/1485188/


All Articles