PDA

View Full Version : Errors occur when using NSOutputStream to transfer big files




carolyn.lee
Apr 28, 2009, 11:22 PM
Hi, All

I'm trying to use the NSOutputStream class to transfer some audio file through Bonjour service which is implemented on the iPhone simulator.I try the following code with some small text files. It works well. But there are always some error occurs() when I try to send the bigger ones -- some audio file.

Any suggestions .... ? Thanks !


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sendFile = [documentsDirectory stringByAppendingPathComponent: @"test1.caf"];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:sendFile] autorelease];

uint8_t *readBytes = (uint8_t *)[myData bytes];
NSUInteger byteIndex = 0;
int myData_len = [myData length];

while (_outStream && [_outStream hasSpaceAvailable]) {

readBytes += byteIndex;
unsigned int len = ((myData_len - byteIndex >= 1024) ? 1024 : (myData_len-byteIndex));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);

len = [_outStream write:(const uint8_t *)buf maxLength:len];
byteIndex += len;
}


Emma



kainjow
Apr 28, 2009, 11:51 PM
Look again at the return values for write:maxLength:. First off you aren't checking for any errors that it may give, and secondly it looks like the assignment of readBytes is being incremented too far. The memcpy() should be unnecessary as well, you could just increment a pointer and pass it directly to the stream.

Also, when you're using -[NSData initWithContentsOfFile:], you're loading the entire file into memory. Since the iPhone has limited ram you should probably replace this with NSFileHandle, which lets you load file data incrementally.

Oh, and put your code in between ... tags - makes it easier to read.

carolyn.lee
Apr 29, 2009, 08:45 PM
I'm sorry for asking the naive questions. I'm new comer, and there are not a lot of documents detailed what I want, so I just try to pull up together the sample code to see how it works.

kainjow, thanks a lot. I tried what you mentioned, it can send data now, but after sending out the data, the simulator terminated abnormally ....

kainjow
Apr 29, 2009, 11:39 PM
Can you post your updated code?