pistacchio
pistacchio

Reputation: 58903

Objective C: Get page content

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

This is what I mean in python

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

or php

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

or c#

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

Thanks

Upvotes: 1

Views: 4800

Answers (3)

mmccomb
mmccomb

Reputation: 13807

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

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"]

Create a NSURLConnection to handle your request...

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

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:

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

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];
}

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.

Upvotes: 5

criscokid
criscokid

Reputation: 640

Check out the documentation for NSURLConnection. This is the asynchronous way to get at it. If you don't mind blocking the thread you can also check out stringWithContentsOfURL:encoding:error: on NSString.

Upvotes: 1

pistacchio
pistacchio

Reputation: 58903

Answer here:

objective c pulling content from website

Just remember to add the framework Webkit

Upvotes: -1

Related Questions