Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - InputStream to NSString

I'm kind of new on Objective C, so I'm trying to do stuff I usually do in Java, like converting an InputStream into a String. Basically, I want to do this Java code in Objective C...

InputStream in = … //An inputStream i got from http request

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;

while ((line = reader.readLine()) != null) {
    str.append(line);
}

String myString = str.toString();
in.close();

I hope my problem is described clear enough! :)

Thanks!

like image 973
JoseLion Avatar asked Jun 16 '26 10:06

JoseLion


2 Answers

Well, Caleb is right, but answering to the question:

NSInputStream *inputStream = [[NSInputStream alloc] init];
uint8_t buffer[1024];
int len;
NSMutableString *total = [[NSMutableString alloc] init];
while ([inputStream hasBytesAvailable]) {
    len = [inputStream read:buffer maxLength:sizeof(buffer)];
    if (len > 0) {
        [total appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]];
    }
}

Your encoding argument could be different.

like image 61
folex Avatar answered Jun 17 '26 23:06

folex


I'm kind of new on Objective C, so I'm trying to do stuff I usually do in Java, like converting an InputStream into a String. Basically, I want to do this Java code in Objective C...

Understandable, but trying to do those things the same way you do them in Java often doesn't work. Things aren't always done in Objective-C the same way that they're done in Java, so you can't just swap in new class names and fix up the syntax a bit. There's an NSInputStream class, but it's not typically used to download data from a web server. In short, you don't get an input stream from an http request. Instead, take a look at the NSURLConnection class and the NSURLConnectionDelegate protocol. Indeed, there's a whole document called URL Loading System Programming Guide that you should read. You'll create a NSURLConnection instance, give it a delegate, and let it do it's thing. The delegate's -connection:didReceiveData: method will be called as data comes in, and the delegate can do whatever it wants with the data, such as adding it to a string.

like image 20
Caleb Avatar answered Jun 18 '26 01:06

Caleb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!