I looked around but I could not find quite the solution to my problem anywhere.
The thing is I would like to get the data that is on a webpage of mine. For example, the content of my web page is “4|3|6” and I would like to have an array with 4,3,6.
I may say something stupid there but I don’t really know if my page is XML or HTML, because when I check the source code it just shows “4|3|6” for example.
So is there any way to do this or am I going to have to look into parsers ? And also, how to know of what type my page is ? (it’s name is typically “http://example.aspx?value=x” )
I know a lot of questions were asked about this and I apologize if I missed the one with my answer in it.
If it helps, here are the info on the page:
type: text/plain
Encoding: UTF-8
EDIT: So after trying Alex’s version, it seems I can’t get to retrieve the data. I think the problem is to get the NSString from the data, which is that line:
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This line doesn’t give me a crash, but when I try to display it using
label.text=datastring;
it doesn’t display anything. And when I try to assign an NSArray from datastring using the @”|” separator, and try for example to display the first item of that NSArray, it gives me that error about index being out of bounds.
I am not at work right now so I can’t really test this but thanks for any ideas.
If the source code is just “4|3|6” it’s plain text. You can download it using
NSURLConnection:Then you can create a string from the data and parse it:
Now you’ll have the components in the resulting array. I’m assuming the data is encoded in ASCII, which might not be the case. And the download is synchronous, which means it will block the current thread. If you’re running the code on the main thread, you might want to dispatch it to a background thread so that you don’t block the UI. But that’s to worry about later, just get it working first.
As for the asynchronous download, I don’t like the asynchronous
NSURLConnectioninterface, as it’s quite a lot of work for what it does. It’s a pity thatNSURLConnectiondoes not support blocks. You can find someNSURLConnectionextensions with blocks on the web, but that means relying on third-party code, which carries its own possible problems. One easy way to get the download happening in background is this:But you should learn about threading, run loops and autorelease pools before you start using this code, so that you know what you are doing.