开发者

NSData / Retrieving content from a page

I have a page that displays one string on a blank page. I need to retrieve that string. How would I do it if I wanted to do it both, synchronously and asynchronously? (I would appreciate if someone gave me the metho开发者_开发技巧d names for both synch and asynch).

Thank you,


You can use NSString's stringWithContentsOfURL:encoding:error: method to get the HTML page synchronously and later parse it using NSXMLParser.

Since stringWithContentsOfURL:encoding:error: is a blocking call, you should put it in a method and invoke the method using performSelectorInBackground:withObject:. This will retrieve the HTML page in the background.

Once you have the string, create an instance of NSXMLParser and get the string. This one is asynchronous process.

Few examples on how to use NSXMLParser - Make NSXMLParser your friend and BNR - Parsing XML in Cocoa.


Have a look at the NSURLConnection reference. The methods you want are there. Also, read the URL Loading guide, it has some code examples for both synchronous and asynchronous loading.

The body data of the repsonse will be the string you want. You'll need to be a bit careful about which encoding was used by the web site. If not specified in the response at all, it will be ISO-8859-1, otherwise it will probably be specified in the Content-Type header of the response. You then need to convert the data to an NSString with initWithData:encoding:

NB if you are not on the main thread, you can use NSStering's stringWithContentsOfURL:usedEncoding:error:. You shouldn't use this on the main thread because it is a synchronous method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜