views:

99

answers:

1

I am currently trying to port a .Net app to Objective C and Cocoa. I know the basics and have had little trouble with most things. But I'm having trouble retrieving data from the Web.

In C# I would use POST and GET to retrieve information from a server as such

byte[] buffer = Encoding.ASCII.GetBytes("someData");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;

Stream postData = request.GetRequestStream();
postData.Write(buffer, 0, buffer.Length);
postData.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());

while (!reader.EndOfStream)
{
   String data = read.ReadLine();
   //Do something such as an update on each line read in
}

reader.Close();
response.Close(); 

but I'm not having much luck finding a Cocoa equivelant. I have seen the use of things such as NSUrlDownload but all the examples I can find always show the download of the data as a single blocking function call. Where what I need is to be able to update things as I recieve data, not just wait for it all to arrive then deal with it. And ideally I would be able to deal with different types of data such as text or binary, so I need something similar to a stream that I can pass to a parser of some kind.

So my question is what is the equivelant of the C# code above?

+3  A: 

You need to use NSURLConnection and assign an object as its delegate. As the connection receives data, it will call the -connection:didReceiveData: delegate method which you can use to process the incoming data as necessary.

You will need to build the HTTP POST request yourself. I have posted some code that shows how to do this in my answer to this question.

Rob Keniger
Thank you very much that worked worked, If I wanted to use your method to send an array of strings to a php script how would I manage that with the dictionary your using?
Tristan
Posting a PHP array is a little difficult because you need multiple values with the same name (`nameOfKey[]`). Obviously an `NSDictionary` can't have multiple keys of the same name, so you'll probably want to create a custom object to hold your data. You could then create a method on that custom object that adds each one of the properties of that object (strings, arrays, numbers etc) to the POST string.
Rob Keniger
Excellent thank you very much for that! One last thing if you can help do you know where I can find out more about the format your putting the post string in? I always like to know the full story :)
Tristan
Have a look at http://en.wikipedia.org/wiki/MIME#Multipart_messages and http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Rob Keniger