我目前正在尝试将 .Net 应用程序移植到 Objective C 和 Cocoa。我了解基础知识,并且在大多数事情上都没有遇到什么麻烦。但我在从网络检索数据时遇到问题。
在 C# 中,我会使用 POST 和 GET 来从服务器检索信息
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();
但我没有太多运气找到 cocoa 等效物。我见过诸如 NSUrlDownload 之类的东西的使用,但我能找到的所有示例始终将数据下载显示为单个阻塞函数调用。我需要的是能够在收到数据时更新内容,而不仅仅是等待所有数据到达然后处理它。理想情况下,我能够处理不同类型的数据,例如文本或二进制,因此我需要类似于流的东西,我可以将其传递给某种解析器。
所以我的问题是上面的 C# 代码的等价物是什么?
最佳答案
您需要使用NSURLConnection
并分配一个对象作为其委托(delegate)。当连接接收数据时,它将调用 -connection:didReceiveData:
委托(delegate)方法,您可以根据需要使用该方法处理传入数据。
您需要自己构建 HTTP POST 请求。我在对 this question 的回答中发布了一些代码,展示了如何执行此操作。 .
关于.Net HttpWebRequest/Response Cocoa 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2772837/