Got Null Value From the api in objective c - ios

I am fetching JSON values from the API...but it showing the values as null... I checked it in the postman it's working there and I have the response...I have listed my sample code below please mention my mistakes. I'm new to this development
- (IBAction)PaymentButtonTapped:(id)sender {
[self PayuMoneyAdminValues];
}
-(void)PayuMoneyAdminValues{
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
NSString *urlstring = [NSString stringWithFormat:#"%#admindatas",restSiteURLServices];
NSURL *url = [NSURL URLWithString:urlstring];
NSString *userUpdate = [NSString stringWithFormat:#"%#",restAuth];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setURL:url];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//NSData *data1 = [NSData dataWithContentsOfURL:url];
//Apply the data to the body
[urlRequest setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data!=nil){
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError) {
NSLog(#"Admin data: %#",responseDictionary);
}
}
}];
[dataTask resume];
}

Related

How to add Dictionary as a Request Parameter For HTTPBody in NSJSONSerialization?

I am creating one demo Web Services Code without using AFNetworking Framework.
My HTTP Request Parameter in Dictionary.
How can I set it on HTTPBody?
MY Code is as follow
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl];
[request setHTTPMethod:#"POST"];
NSString *postString = "Request Parameter";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"requestReply: %#", requestReply);
NSError *jsonError;
NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];
You Can Do like that With AFnetworking and Without Af Networking.
NSString *stringUrl = #"xxx";
NSURLSessionConfiguration *myConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *myManager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:myConfiguration];
AFHTTPResponseSerializer *mySerilizer = [[AFHTTPResponseSerializer alloc]init];
[myManager setResponseSerializer:mySerilizer];
NSDictionary *param = [[NSDictionary alloc]initWithObjectsAndKeys:#"value==",#"Token", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *requestParameter = [NSDictionary dictionaryWithObject:string forKey:#"request"];
[manager POST:stringUrl parameters:requestParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *error;
if(!error)
{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"%#",dict);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
Without Dictionary
NSString *urlString = #"xxxx";
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:configuration];
AFHTTPResponseSerializer *serilizer = [[AFHTTPResponseSerializer alloc]init];
[manager setResponseSerializer:serilizer];
NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:#"value",#"key", nil];
[manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *error;
if(!error)
{
NSDictionary *finalData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Final Data is %#",finalData);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
Without AFNetworking
NSString *MyUrlString = #"xxxx";
NSURL *url = [NSURL URLWithString:MyUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = #"key=value";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];
Note:-Do not forget to put resume
Thank you
Check your condition with my working code,
NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:50.0];
[_request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"]; // Interact your backend developer for header
[_request addValue:#"application/json" forHTTPHeaderField:#"Accept"];// Interact your backend developer for header
[_request setHTTPMethod:#"POST"];
NSError *error;
NSData *_inputData = [NSJSONSerialization dataWithJSONObject:inputDictionary options:0 error:&error];
[_request setHTTPBody:_inputData];
NSURLSessionDataTask *_fetchData = [[[self class] session] dataTaskWithRequest:_request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(!error) {
NSError* error;
completionBlock(data,error,1);
} else {
completionBlock(data,error,0);
}
}];
[_fetchData resume];
Got The Data
NSURL *stringwithUrl = [NSURL URLWithString:#"XXXX"];
NSMutableURLRequest *requestUrl = [NSMutableURLRequest requestWithURL:stringwithUrl];
[requestUrl setHTTPMethod:#"POST"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"Value==",#"Key", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *mainString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *requestString = #"request=";
NSString *finalString = [requestString stringByAppendingString:mainString];
[requestUrl setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *sesion = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[sesion dataTaskWithRequest:requestUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",dict);
}]resume];

IOS: kCFErrorDomainCFNetwork error -1002. Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"

hello all i know this kind of question asked previously but i didn't get any solution from them
in my project i am working in login view when i am put code on login button i am getting an error
Error : Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x7fb37b62c9a0 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x7fb37b715a20 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1002.)"}
but i am using the same code for login which i used in my previous projects and it works fine there
here is my code:
-(IBAction)login:(id)sender
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php?token={LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUc4d0RRWUpLb1pJaHZjTkFRRUJCUUFEWGdBd1d3SlVBeWo0WE9JNjI4cnJRTG9YeEpXNG1zUWI1YmtvYk1hVQpzMnY1WjFKeXJDRWdpOVhoRzZlZk4rYTR0eGlMTVdaRXdNaS9uS1cyL1NCS2pCUnBYUzVGYUdiV0VLRG1WOXkvCkYrWHhsUXVoeER0MEV3YkRBZ01CQUFFPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K}&method=user.getLogin"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"login=abc#gmail.com&password=123456"];//,username.text, password.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"map data is = %#",mapData);
NSURLSessionDataTask * postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse* response, NSError * error) {
if(error == nil)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"jsondic= %#",jsonDic);
NSDictionary *userDataDic = [jsonDic objectForKey:#"data"];
NSLog(#"Dict is %#",userDataDic);
Please help me to resolve it i already see the similar type of questions but didn't overcome from this issue
Any help is appreciated
I tried your code.Except your url the other lines of code is correct.If you pass your corrct URL,it works perfectly.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php"]]; //pass your url here
[request setHTTPMethod:#"POST"];
//Passing The String to server
NSString *strUserId = #"pradeep.kumar#eyeforweb.com";
NSString *strPassword = #"admin123";
NSString *userUpdate =[NSString stringWithFormat:#"login=%#&password=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is %#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"The postData is - %#",data1);
//Apply the data to the body
[request setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];

POST base 64 image string to a server on iOS

To my understanding, to use this website I have to convert an image to a base64 encoded image and then send it to this website. The website will then send me back a number (as a decimal).
https://docs.indico.io/docs/rest-api-image-analysis
I've tried using a number of steps, namely trying to alter a similar process used for sending text and receiving a number. Any tips?
UPDATE:
- (IBAction)press:(id)sender {
//UIImage *imager = photos.image;
NSData *imageData = UIImageJPEGRepresentation(photos.image, 1.0);
NSString *base64Img = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//not sure if #"data" or #"data.json" and whether the base64img should be behind it
NSDictionary *parameters = #{#"data":base64Img};
NSMutableString *parameterString = [NSMutableString string];
for (NSString *key in [parameters allKeys]) {
if ([parameterString length]) {
[parameterString appendString:#"&"];
}
[parameterString appendFormat:#"%#=%#", key, parameters[key]];
NSURL *url = [NSURL URLWithString:#"http://apiv2.indico.io/contentfiltering?key='17767cb46eb4b4f568832be2c953022b"];
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[parameterString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
if ([data length]) {
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//GET RESULT;
NSLog(#"A %#", parameters[#"results"]);
}
} else {
NSLog(#"%#", error);
}
}];
[task resume];
}
the results I get usually return as (null)
maybe try going
NSDictionary *parameters = #{#"data":base64Img};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:nil
error:&error];
//do some error checking
NSURL *url = [NSURL URLWithString:#"http://apiv2.indico.io/contentfiltering?key='17767cb46eb4b4f568832be2c953022b"];
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
//...
just doing this off the top of my head so may need some tweaking
If I had to guess it looks like you've accidentally added a typo to your API key. In the line above:
http://apiv2.indico.io/contentfiltering?key='17767cb46eb4b4f568832be2c953022b
should instead read:
http://apiv2.indico.io/contentfiltering?key=17767cb46eb4b4f568832be2c953022b
Since URL parameters are sometimes quoted and I'm not extremely familiar with objective-c's internal request handling I would guess that that is leading to the strange behavior you're seeing.

How to send POST data using JSON in iOS?

I tried to add an entry to db using a POST request in Objectve-C. My service is:
#RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
#ResponseBody
boolean addEmployee(#ModelAttribute User user) {
try {
logger.log(Level.INFO, user.getCountry());
userDataService.addUser(user);
return true;
//return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return false;//new Status(0, e.toString());
}
}
When I try this on Postman, it's working fine with x-www-form-urlencoded. But when I try this in Objective-C, nothing happens. Here is what I tried:
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[rq setValue:[NSString stringWithFormat:#"%ld", (long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"%#", [error localizedDescription]);
}];
In completion block, the log prints "Could not connect to the server". How can I call the service with JSON data?
Something like this should work
// 1: Create your URL, Session config and Session
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2: Create NSMutableRequest object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
// 3: Create Jsondata object
NSError *error = nil;
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
// Asynchronously Api is hit here
NSURLSessionUploadTask *dataTask =
[session uploadTaskWithRequest:request
fromData:data
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(#"%#", data);
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"%#", json);
success(json);
}];
[dataTask resume]; // Executed First

Is there a 'trick' for sending raw NSString rather than NSData in a NSURLSession connection?

I'm attempting to communicate with a backend using NSURLSession, however, the backend wasn't set up to properly read NSData, so it views the NSData login details I send over as false, I wanna know if its possible to get NSURLSession to send raw strings rather than NSData objects. I've looked in books and the webs and I've been stumped for weeks.
Redoing the backend is not an option, the engineer in charge of that left. Any help is welcome.
Thanks. Here's what I've done so far, in case anyone needs to see some code.
NSError *error;
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration ];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSString *rawUrlString = #"backend_url";
NSURL *url = [NSURL URLWithString:rawUrlString];
NSLog(#"%#", url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
login data here
nil];
//NSLog(#"%#", parameters);
NSData *rawJson = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:rawJson encoding:NSUTF8StringEncoding];
NSData *finalData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:finalData];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"charset"];
[request setValue:#"XMLHttpRequest" forHTTPHeaderField:#"X-Requested-With"];
NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
}];
[postTask resume];
`
UPDATE: I've cleaned up the unnecessary bits this is the final code (still doesn't work though)
NSError *error;
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration ];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSString *rawUrlString = #"backend_url";
NSURL *url = [NSURL URLWithString:rawUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:login details nil];
NSData *rawJson = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:rawJson];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
}];
[postTask resume];
Your backend is setup to handle NSData. It's impossible to send a string over an internet connection, you can only send NSData and all servers expect it.
This code here is wrong:
NSData *rawJson = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:rawJson encoding:NSUTF8StringEncoding];
NSData *finalData = [myString dataUsingEncoding:NSUTF8StringEncoding];
Instead just do this:
NSData *finalData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
The NSData object will contain a string in the correct format for the server to also recognise as a string. Note it will be in UTF-8 encoding, perhaps on some servers you will want to change that to something else.

Resources