Passing JSON as parameter in URL objective-c - ios

I have following web service url:
NSString *url = #"https://api.parse.com/1/classes/Cinema?keys=name,rows,column&where={\"location\":{\"__type\":\"Pointer\",\"className\":\"Location\",\"objectId\":\"gSEpGR28iT\"}}";
here parameter for where is itself in JSON format
Problem is when i consume this web service using following code it gives error:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = #"GET";
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:PARSE_APPLICATION_ID_VALUE forHTTPHeaderField:PARSE_APPLICATION_ID_KEY];
[request addValue:PARSE_REST_ID_VALUE forHTTPHeaderField:PARSE_REST_ID_KEY];
[NSURLConnection sendAsynchronousRequest:command.request
queue:self.operationQueue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
...
}]
Error: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo={NSUnderlyingError=0x7c989590 {Error
Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL"
UserInfo={NSLocalizedDescription=unsupported URL}},
NSLocalizedDescription=unsupported URL}
If i use same web service without where parameter i.e. only https://api.parse.com/1/classes/Cinema?keys=name,rows,column code works fine. I don't know why a parameter in json format is causing problem. Any help would be highly appreciated. Thanks.

Related

Xcode https call to Restful API

I am having an issue in making a call to our RESTful API. The request is to get the token from the API; I need that token to use it to make further calls on that API.
The issue is that whenever I make that call, I get HTTP 403 status code and I don't know why. I am making the same calls from Android but they work fine without any issue.
Actually I have no experience at all to work with xCode; I am just implementing some changes in the existing code which was written by some other developer. I don't know if I am doing something wrong or what.
id keys[] = {#"grant_type", #"client_id", #"client_secret", #"username", #"password"};
id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"https://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
if(data.length > 0 && connectionError == nil) {
NSLog(#"Response --> %# ", response);
}
}
];
Can someone try to help me figure out what is actually going wrong?
Thanks in advance.
I ran your code and the log, i am getting is
Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified
hostname could not be found." UserInfo=
{NSUnderlyingError=0x608000059aa0 {Error Domain=kCFErrorDomainCFNetwork
Code=-1003 "A server with the specified hostname could not be found."
UserInfo={NSErrorFailingURLStringKey=http://oauth-
test.websitename.com/token, NSErrorFailingURLKey=http://oauth-
test.websitename.com/token, _kCFStreamErrorCodeKey=8,
_kCFStreamErrorDomainKey=12, NSLocalizedDescription=A server with the
specified hostname could not be found.}},
NSErrorFailingURLStringKey=http://oauth-test.websitename.com/token,
NSErrorFailingURLKey=http://oauth-test.websitename.com/token,
_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8,
NSLocalizedDescription=A server with the specified hostname could not
be found.}
I tried it with NSUrlSession also but it is giving same problem.
I think your server is not configured
Below is the code with URL session
id keys[] = {#"grant_type", #"client_id", #"client_secret",
#"username", #"password"}; id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id); NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"]; [request setHTTPBody:jsonData];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask *dataTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(#"%#", response);
}];
[dataTask resume];

Getting Frequent Time out

I am Getting Frequent Timeout errors (not always but some times)although the timeout is set 500 .Chekd the same on postman too Two things one in postman the connection is always keep alive and second one is "The request timed out" coming randomly not always .BUt it just happen as soon as screen opened as i have called the webservice in ViewDidload so it has to at-least wait a bit .before throwing the error
what might be the possible cause for this
Below is my implementation for request
+(void)placeRequest:(NSString *)action parametersString:(NSString*)postDataStr withHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#%#", IOS_BASE_URL, action];
NSURL *url = [NSURL URLWithString:urlString];
NSDictionary *headers = #{ #"content-type": #"application/x-www-form-urlencoded",#"Connection":#"keep-alive", #"cache-control": #"no-cache"};
NSString *parmetersToPost=[NSString stringWithFormat:#"%#%#",postDataStr,[AppDelegate UserWebCommeParmeters] ];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[parmetersToPost dataUsingEncoding:NSUTF8StringEncoding]];
NSString *logString=[NSString stringWithFormat:#"Here the Url is : \n\n\n\n %# \n\n\n\n\nAction Used is :========> %# \n\n\n\n\n and the Parmeter posted are :=============> %#",IOS_BASE_URL,action,parmetersToPost];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:500.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSLog(#"All header Sent are %#", request.allHTTPHeaderFields);
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock] resume];
}
Calling this method as below in viewdidload
[HttpRequest placeRequest:#"check_value" parametersString:postData withHandler:^(NSData *receivedData, NSURLResponse *response, NSError *err){
}];
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."
UserInfo={NSErrorFailingURLStringKey=http://cms.xa.com/apps/xa/ax/myFuntion,
_kCFStreamErrorCodeKey=-2102, NSErrorFailingURLKey=http://cms.xa.com/apps/xa/ax/myFuntion,
NSLocalizedDescription=The request timed out.,
_kCFStreamErrorDomainKey=4, NSUnderlyingError=0x16587760 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)"
UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}

When I query the google datastore my response is 'not found'

When I query the google datastore (after authenticating from iOS) - the response from my NSURLConnection is 'Not Found'. I am expecting to see something like 'missing parameters from post', or like on this site, where it says '503 service unavailable' or something like that.
https://developers.google.com/apis-explorer/#s/datastore/v1beta2/datastore.datasets.runQuery
The code is
NSString *url = #"https://www.googleapis.com/datastore/v1beta2/datasets/MYDATASETID/runQuery?key=MY_API_KEY";
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response is %#", stringData);
}];
Where MYDATASETID is my actual project name. And I am getting these instructions for this url from the site:
https://developers.google.com/datastore/docs/apis/v1beta2/datasets/runQuery
thanks
The answer for me to get a response was to set 'POST' as the HTTP Method, for example:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullUrl]];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[someData dataUsingEncoding:NSUTF8StringEncoding]];
Note though that this does not fully solve my challenge because although I get a response, the response from my variable stringData is
Login Required
And the error in NSError *connectionError is
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x8e20690 {NSErrorFailingURLKey=https://www.googleapis.com/datastore/v1beta2/datasets/MY_APP_ID/runQuery?key=MY_APPS_API_KEY, NSErrorFailingURLStringKey=https://www.googleapis.com/datastore/v1beta2/datasets/MY_APP_ID/runQuery?key=MY_APPS_API_KEY, NSUnderlyingError=0x8d6f120 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}

get method in ios json parsing issue

I just want to hit URL :
http://kiascenehai.pk/rest_api/todayEvents/api-key/Of7NU7Jimh665D5G5VwO2eKO69sWv9lf/format/json
and parameter is city_id.i.e: /city_id/1 but; compiler creates Error
Domain=NSURLErrorDomain Code=-1002
"unsupported URL"
or
error 300;
so what shall be best way to pass arguments in a method in objective c???it also causes Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error 303
It will be pleasure for me if any one can reply me fast as possible.
Unable to reproduce issue you have mentioned, Probably the issue 'll be not because of the URL or parameters you used.
This is one of the best way to handle GET web service call and parsing data from the response, here i implemented the web call with your URL and params,
// Server data fetch
- (void)getDataForCityId:(NSInteger)cityId
{
NSMutableString *urlString = [#"http://kiascenehai.pk/rest_api/todayEvents/api-key/Of7NU7Jimh665D5G5VwO2eKO69sWv9lf/format/json/city_id/" mutableCopy];
[urlString appendFormat:#"%d", cityId];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
id jsonObj = [self parseJSON:data];
}
}];
}
// Method parses the JSON Data Received
- (id)parseJSON:(NSData *)data
{
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
return jsonData;
}
The jsonObj parsed form the response is as

Getting Error Domain=kCFErrorDomainCFNetwork Code=-1000 or NSCocoaErrorDomain Code=3840

First of i want to tell you its a duplicate question, but i have tried all the ways possible
- link I have searched--> Bad URL when requesting with NSURL
iOS Develoment: Why is my NSURLConnection failing with a "bad URL" error for only some users?
Bad URL when requesting with NSURL
I am sending a request to server-> but am always getting bad URL error i.e
Request Failed with Error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xcbf0680 {NSUnderlyingError=0xc9ad8e0 "bad URL", NSLocalizedDescription=bad URL}, {
NSLocalizedDescription = "bad URL";
NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1000 \"bad URL\" UserInfo=0xc96dc30 {NSLocalizedDescription=bad URL}";
}
Code->
NSString *imgUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture", fbid];
NSString *urlString = [NSString stringWithFormat:#"%#url=register_user.json&username=%#&email=%#&dob=%#&by_socialnetwork=\"1\"&gender=%#&nicename=%#&socialimageurl=%#",BASE_URL,[info_dict objectForKey:#"username"],[info_dict objectForKey:#"email"],[info_dict objectForKey:#"birthday"],[info_dict objectForKey:#"gender"],[info_dict objectForKey:#"name"],imgUrl];
NSLog(#"url %#",urlString );
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
[request setHTTPMethod:#"GET"];
[request addValue:#"text/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSLog(#"url %#",request );
AFJSONRequestOperation *operation=[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"dgj,gfj,gf,j%#",JSON);
[self requestSucceedWithItems:JSON forRequestType:#"FB"];
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
[appdelegate showAlert:#"Error" forText:#"Network activity failed,Try later."];
}];
[operation start];
terminal NSLOG Response:-
url <NSURLRequest: 0xcd8d060> { URL: http://192.168.1.100/~ha/gokk/index.php?url=register_user.json&username=abx&email=abxx#gmail.com&dob=12/19/1978&by_socialnetwork=1&gender=male&nicename=Sam&socialimageurl=https://graph.facebook.com/1008823838/picture }
Response:-
****Sometime i am getting BAD url Error or this ****
2014-02-06 13:37:01.426 Flokk[1561:a0b] Request Failed with Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0xc953c20 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}, {
NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";
}

Resources