consume json webservice from IOS with null - ios

I use code like the following
NSString *urlAsString = [NSString stringWithFormat:#"urladdress", coordinate.latitude, coordinate.longitude, PAGE_COUNT, API_KEY];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSLog(#"%#", urlAsString);
but I have web service method that take string as parameter (may be null or empty) how to create the url of this method
I tried http://EgySchools.com/datawebservices/getcategories
how to continue to add the parameters

Related

NSURL with JSON returns null

I'm keep getting a (null) error when I try to build my NSURL to open another app.
The URL should be
ms-test-app://eventSourceId=evtSrcId&eventID=13675016&eventType=0&json={"meterresults":[{"clean":"2","raw":"2","status":"0"}]}
but when I try to build my URL it's always null.
At first I thought it has something to do with the URL itself, but it's the same as I got it from the example here.
Another thought was that IOS got some problems with the double quotes in the JSON, but I replaced them with %22, but this doesn't work either.
Here is the code, where I build the URL:
NSString *jsonString = [NSString stringWithFormat:#"{%22meterresults%22:[{%22clean%22:%22%#%22,%22raw%22:%22%#%22,%22status%22:%22%#%22}]}", cleanReadingString, rawReadingString, status];
NSLog(#"JSON= %#",jsonString);
//Send the result JSON back to the movilizer app
NSString *eventSourceId = #"evtSrcId";
NSString *encodedQueryString = [NSString stringWithFormat:#"?eventSourceId=%#&eventID=%d&eventType=0&json=%#",
eventSourceId, _eventId, jsonString];[NSCharacterSet URLQueryAllowedCharacterSet]]
NSString *urlStr = [NSString stringWithFormat:#"%#%#",
[_endpointUrls objectForKey:[NSNumber numberWithInt:(int)_selectedEndpoint]],
encodedQueryString];
NSURL *url = [NSURL URLWithString:urlStr];
I don't know where I'm wrong and I would be glad if someone got any idea.
Thanks in advance.
You should really be using NSURLComponents to create URLs rather than trying to format them into a string.
NSDictionary* jsonDict = #{#"clean": #"2", #"raw": #"2", #"status": #"0"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:NULL];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSURLComponents* components = [[NSURLComponents alloc] init];
components.scheme = #"ms-test-app";
components.queryItems = #[
[[NSURLQueryItem alloc] initWithName:#"eventSourceId" value:eventSourceId],
[[NSURLQueryItem alloc] initWithName:#"eventID" value:#(_eventId).stringValue],
[[NSURLQueryItem alloc] initWithName:#"json" value:jsonString]
];
NSURL* url = components.URL;
Once you build the URL that way, it becomes apparent that your string doesn't have a host portion (or more accurately, one of your parameters is being used as the host portion).
The other comments about not being able to send JSON as an URL parameter are incorrect. As long as the system on the other side that is parsing the query string can handle it, you can send anything you want as an URL parameter.

How do I add a number to an NSURL? Too many arguments error

I've got a small problem that seems a little bit odd to me. I often used NSString or NSLog while adding NSNumbers into several places:
NSNumber *categoryId = [[NSNumber alloc]initWithInt:0];
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
Now xcode tells me that I'm too many arguments. What am I doing wrong? Setting up an NSNumber into NSStrings or NSLogs works as I did it above.
Best Regards
What is wrong is on
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
you are calling URLWithString: and then pass in a string that is not being formatted correctly. If you want to do it all on one line then you need to be using stringWithFormat: like
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]]];
Because it is adding a parameter you can't just create a string like you normally would with #"some text" you need to format it using the stringWithFormat: which will return an NSString * with the text held within #"" and the paramters you pass in. So [NSString stringWithFormat:#"My String will come with %#", #"Apples"]; this would provide an NSString with "My String will come with Apples". For more information check out the Apple Documentation for NSString and stringWithFormat:
Try this :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.phpaction=getCategoryByCategory&category=%i", [categoryId integerValue]]];
Initially code was wrong because of : "categoryId integerValue]" (I forgot a '[').
You can use NSString to form your NSURL. You can then pass it to your URLWithString like below:
NSNumber *categoryId = [NSNumber numberWithInteger:0];
NSString *urlString = [NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
NSURL *url = [NSURL URLWithString:urlString];

Creating NSURL with custom query parameter returns nil

I have a UISearchBar from which I'm extracting the text that represents an address and building from it a JSON URL for Google Geocoder.
NSString* address = searchbar.text;
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", address];
If I copy & paste the url from debug window to the browser it works like a charm but when I try to convert it to NSURL i get nil
NSURL* theUrl = [NSURL URLWithString:url];
Any ideas?
I added the encoding to the address prior to concatenating the url and that fixed the problem so now the code looks like this:
NSString* address = searchbar.text;
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, CFBridgingRetain(address), NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8));
NSString* url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false", encodedString];

Social framework auto-appending access key

I am attempting to retrieve a list of friends with specific fields using the iOS 6 Social Framework. I am using the URL:
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"fbUserID"];
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#/friends?fields=id,name,picture", username];
NSURL *friendsList = [NSURL URLWithString:urlString];
But the framework seems to be appending the access key to it automagically, and is doing so with a '?' as if it were the first URL parameter. What's more, the API is complaining that it was expecting the end of the statement and not a ?, as is evident in this error:
error = {
code = 2500;
message = "Syntax error \"Expected end of string instead of \"?\".\" at character 15: id,name,picture?access_token=HHyDtnfrjnojngehrtjgnekngeXsI0ZBansnfjDHDhljoQKIfZB5i3JMUHlJIm5HHdwM4s5ixyu38es1vj9XXTcLSS6ZCOi13zQW87dw9YP3DgpllDz5KB6WnSeYGxS9RMfd3npZBwZAEUdmkJHoYlWvflfcQHVwIydLfExjOaNpGZBGhYvb3XlrZAXt7jmDai6FiMoZBRmdOUWfA5vubeNbvvn9y80cPaUPZBZCAZDZD";
type = OAuthException;
};
Is this normal behavior for the framework? Is the access token usually appended in this manner? If so, how should I form my urlString so that this is not a problem?
Instead of putting the "fields" param in the NSURL, try creating just a plain NSURL
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#/friends", username];
NSURL *friendsList = [NSURL URLWithString:urlString];
And call requestForServiceType:requestMethod:URL:parameters, and pass in something like:
#{#"fields": #"id,name,picture"}
for the "parameters" field.

Data argument not used by format string but it works fine

I used this code from the Stack Overflow question: URLWithString: returns nil:
//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
When I copied it into my code, there wasn't any issue but when I modified it to use my url, I got this issue:
Data argument not used by format string.
But it works fine. In my project:
.h:
NSString *localisationName;
.m:
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
How can I solve this? Anything missing from my code?
The # in the original string is used as a placeholder where the value of webName is inserted. In your code, you have no such placeholder, so you are telling it to put webName into your string, but you aren't saying where.
If you don't want to insert webName into the string, then half your code is redundant. All you need is:
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
The +stringWithFormat: method will return a string created by using a given format string as a template into which the remaining argument values are substituted. And in the first code block, %# will be replaced by value of webName.
In your modified version, the format parameter, which is #"http://en.wikipedia.org/wiki/Hősök_tere", does not contain any format specifiers, so
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
just runs like this (with the warning Data argument not used by format string.):
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";

Resources