fetching data from URL in objective c - objective-c

I am making iPad application, in which, I am fetching data from a URL. Sometimes, I retrieved Null instead.
In my URL i am passing my id dynamically, for eg: in this code i passed id = PNB,
here is the code snippet:
NSMutableString*str;
NSString *urlAddress = #”http://ipad.idealake.com/stockquote.aspx?id=PNB”;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
str=[NSMutableString alloc] initWithContentsOfURL:url]; //(here compiler shows me warning initWithContentsOfURL is deprected)
NSLog(#"str=%#",str);
When I do NSLog of str, it shows me null value,
output: str=null
However, when I pass id=SUNPHARMA or id=AMBUJA it shows me proper output but when i pass id=TCS or id=LT it again shows me null value in my str. What went wrong?

you have to trim your id , and try...

The reason for getting nil is probably because the id argument is sometimes wrong (TCS or LT). Double check them, the URL probably hasn't any information to give in response.
About the warning, as stated in the doc, the initWithContentsOfURL: method is deprecated since iOS 2.0, you are encouraged to use initWithContentsOfURL:encoding:error: instead.

PLease use ASIHTTPRequest LIB to solve all your problem. They do download data to memory or directly to a file on disk, cache responses and download progress indicators for operation queues. http://allseeing-i.com/ASIHTTPRequest/

Related

NSURL escaped characters don't work

I'm having a problem with creating an NSURL object using an URL string which looks like this:
"... fexp=935648%2C945012%2C901066%2C91 ..." and so on (it's just a part - the complete URL is very long).
The URL contains many percentage escaped characters (%2C). I am absolutely not able to create an NSURL object with this URL (the URL itself is correct, as I can open it using a browser). The call to
[[NSURL alloc] initWithString:url];
returns NIL.
As soon as I modify the url by calling
[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
I receive a valid NSURL object.
Problem is: this "valid" NSURL object contains an invalid URL which looks like this:
"... fexp=935648%252C945012%252C901066%225C91 ..."
As you can see the initial percent escaped character (%2C) has been escaped again (%252C) which results in an URL which cannot be opened (tried it using a browser again).
The original URL is generated by an external tool so I don't have any influence on its creation mechanism.
Does anybody have a clue what might be wrong?
To me it seems a little bit strange but the following seems to work:
[url stringByRemovingPercentEncoding];
[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];`
Thanks for the hints.

How to parse base64 image from JSON

What's the reason that I can't parse a base64 string from a JSON request? when I make it a small string it works.
To clarify a little:
else if([connection isEqual:self.appearanceConnection]){
NSArray *arrayOfAppearances = [NSJSONSerialization JSONObjectWithData:[[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingAllowFragments error:&error];
NSLog(#"het aantal appearances is: %i", arrayOfAppearances.count);
[self syncAppearances:arrayOfAppearances];
}
When I edit it to a small string, I get the response that the length of the received array is 1. If I change it again to the base 64 of the image, the length is 0.
http://cl.ly/image/470Z0X1P3K1b (image form JSON response)
The error I get on the String:
Updated answer:
You now inform us that JSONObjectWithData is reporting an error:
Unterminated string around character 62
Character 62 is the start of the logo. I'm not seeing the end of the JSON in any of your screen snapshots. It looks like it's getting cut off.
You haven't shown us how you are populating data, but it looks almost like you're using a NSURLConnection but trying to parse in didReceiveData as opposed to waiting for the full results and only invoking the the JSON parse in connectionDidFinishLoading. NSURLConnection will break a long response into several calls to didReceiveData and you have to append all of those NSData to a single NSMutableData, and only try to parse it when it's done retrieving everything.
You either need to (a) show us the code where you're loading data and/or (b) share the full JSON. Either your JSON isn't properly terminated or you're trying to parse it before the whole thing is downloaded (probably the latter).
Original answer:
I'm not sure if this is the problem, but your line that says:
NSArray *arrayOfAppearances = [NSJSONSerialization JSONObjectWithData:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingAllowFragments error:&error];
should simply be:
NSArray *arrayOfAppearances = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
The JSONObjectWithData method takes a NSData, not a NSString.
And, if you're not getting anything returned from this method, you should examine the contents of error and see what it says.
If you're still unable to figure out what the problem is, perhaps you can share the full JSON response with us (give us a URL or upload it somewhere) and we can take a look at it.
With a big thanks to #Rob!
Here a little summary:
Create a variable NSMutableData (don't forget to initialise in the viewdidload)
In the didReceiveData, you append the data to your mutable data using [self.appearancedata appendData:data];
In the connectionDidFinishLoading you parse your JSON

Log ASIFormDataRequest body as NSString

I'm making a multipart request to server using ASIFormDataRequest, and I want to review the post body myself before the request is actually made. Is there any way I can print it to console or something like that?
Turned out that I just needed to
#define DEBUG_FORM_DATA_REQUEST 1
After that, the library logs all post body to console (except for binary data, which is truncated).
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setStartedBlock:^{
NSLog(#"setStartedBlock", request.requestHeaders);
}];
...
[request startAsynchronous];
The StartedBlock is the very last callback before the connection is actually made to the server.
You can log your entire header using what I posted or if you want just the post data you can use the NSLog james had.
You can try:
NSLog(#"%#", dataRequest.postData);
If you can include some code it would be helpful.
I can't comment answers right now so I'll create an answer:
As James Paolantonio said, you can NSLog dataRequest.postData, but only thing you need to do: make this property public by moving code
#property (retain) NSMutableArray *postData;
from ASIFormDataRequest.m to ASIFormDataRequest.h

AVAudioPlayer returns nil at random

I have the following lines in my code:
NSString *soundPath = [[NSBundle mainBundle] pathForResource:[[soundString componentsSeparatedByString:#"."]objectAtIndex:0] ofType:#"wav"];
NSURL *soundURL_ = [NSURL fileURLWithPath:soundPath];
av_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL_ error:nil];
These lines are in a class calles AnimatableObject which i use about 10 to 30 times in one ViewController.
It all works perfectly the first few times the ViewControllers get initialized and loaded. But after switching the ViewControllers some time my app crashes because the following line (which had worked all the times before) returns nil right now.
av_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL_ error:nil];
I checked if soundPath or soundURL_ are nil. But they are ok. Exactly the same value like all the times before when it worked.
So now I ask myself how can it happen, that it works a lot of times and than returns nil?
In the same app, without closing and starting it again. And all I do is switching between viewControllers.
I first thought it is an memory issue, but i don't get any memory warnings.
I really have no idea why this is happening.
Any help would be appreciated.
Thx in advance,
Maverick.
--------Edit--------
I now found out that i get the following error:
ImageIO: CGImageRead_mapData 'open' failed '/var/mobile/Applications/F3186E1A-BBC2-47A6-8EF6-90F73C9BD566/huckla_zoo.app/Weiter.png'
error = 24 (Too many open files)
so i realize that i cannot open a soundfile when i get this error.
Only thing i wonder now is:
How can i close file-handles?
I don't load the images via [UIImage imageNamed:] but with
[UIImage imageWithContentsOfFile:filename];
I also have implemented a MutableDictionary as image cache which gets emptied, when memory issues occur.
Is there any other option for me to close my file-handles?
TRY THIS,
NSString* URL = [YOUR_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
From the error, it sounds like you've opened a lot of files, and forgotten to close them. Are you releasing file objects when you're done? How many files are you working with?

Get XML from NSWebView

I have a NSWebView in which there is loaded XML data. I cannot get it with stringByEvaluatingJavaScriptFromString because JavaScript doesn't want to work with XML. How the hell am I supposed to get it? Why is it so annoying difficult to do something so simple? Creating XML from URL won't work.
How do I get XML from NSWebView into a NSString?
Do you need to use the WebView? I'd suggest just grabbing the data by itself:
NSString *content = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"example.com"]];
I've worked it out myself. Thing is that you have to take the xml from WebFrame and not from WebView. You can then convert the data into a string or whatever you need.
NSData *xmlData = [[myWebView mainFrame] dataSource] data];