Some time when I call this piece of code *data is nil. It works most of the times except for certain situations which I'm not able to find.
Does anyone know why data could be nil and under which circumstances it could happen?
Some times *data isn't nil but it isn't what I'm expecting (for example I'm getting "login_okit_IT" instead of "login_ok")
Here is the code:
+ (NSDictionary *)eseguiRichiestaConURL:(NSString *)urlScript
{
NSString *rawStr = [NSString stringWithFormat:#""];
NSData *data = [rawStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlScript];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
//[request setTimeoutInterval:10000];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"%#", responseData);
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"%#", responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
if(responseData == nil)
NSLog(#"------ PARAMETRI VUOI -------");
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
return dict;
}
Thanks in advance.
Related
Below is my code, and am trying to parse a JSON; I am getting response but when am printing dictionary, it's null.
below is the response string, result of JSON.
NSString *post = [[NSString alloc] initWithFormat:#"jobid=%#",idjob];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:#"URL"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"login:%#",str);
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"aarraa:%#",jsonDict);
Response for str :
{"Jobdesc":[{"jobid":"11260","job_title":"Linux + Nagios System Administrator","job_desc":"<p>Technical skills required:</p>
<ol>
<li>Should be ready to work during French timings</li>
<li>Linux Certification / training is a must</li>
<li>Linux System administration (Red hat Linux, CentOS Servers)</li>
<li>Experience in LAMP configuration and troubleshooting</li>
<li>Knowledge on windows OS</li>
<li>Experience on monitoring tools like Nagios / Centreon, Ops5</li>
<li>Scripting in Shell, Perl or Python</li>
</ol>
","job_role":"Linux + Nagios System Administrator","job_exp":"1-5 year","job_education":"Others","job_location":"Delhi","job_address":"Delhi","job_company_name":"Pandya Business Solutions.","job_company_url":"http://www.pandyabusinesssolutions.com/","job_company_email":"singhjapesh#gmail.com","job_status":""}]}
but parameter jsonDict is null.
Try this...
NSString *jsonString = [NSString stringWithFormat:#"URL"];
NSURL *nurl = [NSURL URLWithString:jsonString];
NSData *jsonData = [NSData dataWithContentsOfURL:nurl];
NSError *error = nil;
NSDictionary *dictResult = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
It seems that you are trying to serialise your data just before you completely get it, below is the code with completionHandler which will begin further process once you get all your data, so try this:
[NSURLConnection sendAsynchronousRequest: theRequest queue [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
}];
i tried validating JSON response, and found that there were extra spaces in JSON so below is my resolved answer.
NSString *post = [[NSString alloc] initWithFormat:#"jobid=%#",idjob];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:#"http://ncrjobs.in/webservice/jobdesc.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSCharacterSet *spaces=[NSCharacterSet whitespaceCharacterSet];
NSPredicate *predicates=[NSPredicate predicateWithFormat:#"SELF !=''"];
NSArray *temparray=[[str componentsSeparatedByCharactersInSet:spaces]filteredArrayUsingPredicate:predicates];
str=[temparray componentsJoinedByString:#" "];
NSString *string = [str stringByReplacingOccurrencesOfString:#"[\r\n]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, str.length)];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
Serialize data like this.
NSMutableDictionary *json =[NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
sometimes I get error "index 1 beyond bounds for empty array" at this line
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This is my full code
+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
return json;
}
Sometimes I get error, Sometimes not. I don't understands ? please help me, thanks everyone.
Whenever you get an error like the above, try the following:
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
if (error)
{
//1. See what the error says
NSLog(error.localizedDescription);
//2. Convert the original data into a string
NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];
//Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
cachePolicy: defaultCachePolicy
timeoutInterval: defaultTimeoutInSeconds];
plz change your cachePolicy with defaultCachePolicy and try :)
I have a simple app which makes a POST request. And then data is returned. The problem is that the returned data is not JSON..... So how can I view it? Here is my code:
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The responce:\n\n%#", responseData);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}
This is the format of the returned data that I am trying to read:
new_token=509723045780uIRBWRBH24b
So I know the downloaded data gets stored in the NSData called "responseData". But if I print it using NSLog I just get this:
<61636365 73735f74 6f6b656e 3d313538 32353838 33343337 39343431 7c365f4d 6543436e 6b51716f 722d6e70 61746662 484d6458 526b3477>
So how do I read this???
Thank you for your time, Dan.
To get NSString from NSData use
NSString *decodedString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
maybe this string will have a valid JSON format.
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
*id json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];*
NSLog(#"%#", json);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}
I am trying to call a web service with these parameters:
{"Class":"Authorization","method":"login","user":"","pass":""}
as follows
NSString *user = [NSString stringWithFormat:#"username=%#",_username.text];
NSString *pass = [NSString stringWithFormat:#"password=%#",_password.text];
NSString *Class = #"Authorization";
NSString *method = #"login";
//NSString *post = [NSString stringWithFormat:#"%#&%#&%#&%#", user, pass, Class, method ];
NSString *jsonPostBody = [NSString stringWithFormat:#"'json' = '{\"Class\":"
"\"%#\""
",\"method\":"
"\"%#\""
",\"pass\":"
"\"%#\""
",\"user\":"
"\"%#\""
"}'",
[Class stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[method stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[pass stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[user stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:#"http://212.119.87.45:8080/IktissabServices/index.php/service"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:180.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES]];
[request setHTTPBody:postData];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:#"%d", [postData length]];
[request setValue:postDataLengthString forHTTPHeaderField:#"Content-Length"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
if (! error) {
NSLog(#"%#",jsonDict);
}else{
NSLog(#"%#",error.localizedDescription);
}
Every time the result is:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'data parameter is nil'
The web service has:
input-content-type: text/json
output-content-type: text/json
Any help or examples will be appreciated.
I'm not getting any exception with the following code (though obviously I don't have access to your server, so I can't test it end-to-end):
NSDictionary *dictionary = #{
#"Class" : #"Authorization",
#"method" : #"login",
#"pass" : _password.text,
#"user" : _username.text
};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary
options:0
error:&error];
if (error)
NSLog(#"Failure to serialize JSON object %#", error);
NSURL *url = [NSURL URLWithString:#"http://212.119.87.45:8080/IktissabServices/index.php/service"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:180.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
NSLog(#"%s sendSynchronousRequest error %#", __FUNCTION__, error);
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];//
if (!error) {
NSLog(#"%#",jsonDict);
} else {
NSLog(#"%s JSONObjectWithData error %#", __FUNCTION__, error);
}
Or, if you're not using the latest Xcode and don't have access to the Modern Objective C definition of the dictionary, you could obviously define your dictionary the traditional way:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"Authorization", #"Class",
#"login", #"method",
_password.text, #"pass",
_username.text, #"user",
nil];
Edit:
Inferring from your jsonPostBody, the dictionary entry might need to be:
NSDictionary *dictionary = #{
#"json" : #{
#"Class" : #"Authorization",
#"method" : #"login",
#"pass" : _password.text,
#"user" : _username.text
}
};
or possibly (though, even less likely), inferring from your user and pass definitions:
NSDictionary *dictionary = #{
#"json" : #{
#"Class" : #"Authorization",
#"method" : #"login",
#"pass" : [NSString stringWithFormat:#"password=%#",_password.text],
#"user" : [NSString stringWithFormat:#"username=%#",_username.text]
}
};
It's a question of how the JSON needs to be formatted for your server.
Someone please help me in this query.
How to Get JSON data From a URL Which contains .SVC file in iphone (ios5)?
The link is like : http://156.160.45.118/api/Login.svc?wsdl (not original)
and parameters are: email and password.
So how can I verify the login credentials?
My code :
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://156.160.45.118/api/Login.svc?wsdl";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
}
Finally i got my answer By researching lot of things.
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = http://156.160.45.118/api/Login.svc/login;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);