目标 C:获取页面内容 [英] Objective C: Get page content

查看:61
本文介绍了目标 C:获取页面内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从控制台应用程序或库中获取网页内容?我的意思是,没有 UI 元素.

how to get a web page content from a console application or library? I mean, no UI elemens.

这就是我在python中的意思

This is what I mean in python

from urllib import urlopen
str = urlopen("http://www.google.com").read()

或 php

$str = file_get_contents('http://www.google.com');

或 c#

using System.Net;
WebClient client = new WebClient();
string str = client.DownloadString( "http://www.google.com" );

谢谢

推荐答案

NSURLConnection 是 Cocoa 中使用的类,它的用法非常简单...

NSURLConnection is the class to use in Cocoa, it's usage is pretty straightforward...

首先,您需要创建一个 NSURLRequest 实例,其中包含您希望读取的 URL...

Firstly you need to create an instance of NSURLRequest that encompasses the URL you wish to read...

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]

创建一个 NSURLConnection 来处理您的请求...

Create a NSURLConnection to handle your request...

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

注意 init 方法的第二个参数是一个委托.这个委托需要实现以下一组方法...

Note the second parameter of the init method is a delegate. This delegate needs to implement the following set of methods...

connection:didReceiveResponse:
connection:didReceiveData:
connection:didFailWithError:
connectionDidFinishLoading:

在初始化 NSURLConnection 后,下载将开始.您可以随时通过向对象发送取消消息来取消它.

Upon init of the NSURLConnection the download will commence. You can cancel it at any point by send the object a cancel message.

一旦您有要读取的数据,连接将调用 connection:didReceiveData: 其委托上的方法,将 NSData 的实例作为第二个参数传递.当您的连接向您传输数据时,此方法将被多次调用,因此请使用 NSMutableData 的实例来聚合响应...

Once you have data to be read the connection will call the connection:didReceiveData: method on it's delegate passing an instance of NSData as the second parameter. This method will be called multiple times as your connection streams you data so use an instance of NSMutableData to aggregate the response...

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [mutableData appendData data];
}

一旦读取了 URL 的全部内容,就会调用 connectionDidFinishLoading:(NSURLConnection*) 方法.此时释放连接并使用您的数据.

Once the full contents of the URL have been read the connectionDidFinishLoading:(NSURLConnection*) method is invoked. At this point release the connection and use your data.

这篇关于目标 C:获取页面内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆