I have gotten this JSON data back and I would like to parse it into the 3 categories: "guid", "exponent", and "modulus". How would I do that? Thank you for the help in advance!
2015-07-01 11:02:51.972 Acculunk KeyPad[4717:1667358] Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}
2015-07-01 11:03:37.175 Acculunk KeyPad[4717:1674710] Terminating since there is no system app.
Here's the code:
NSString *temp2 = [NSString stringWithFormat:#"{\n \"partner_key\": \"%#\",\n \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n \"payment_account_id\": \"%#\",\n \"card_number\": \"%#\",\n \"card_exp_date\": \"%#\",\n \"amount\": \"%#\",\n \"memo\": \"%#\",\n \"recipient\": {\n \"email\": \"%#\",\n \"mobile_phone\": \"%#\"\n }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);
NSURL *URL = [NSURL URLWithString:#"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:body options:nil error:&e];
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"];
NSString *modulus = res[#"modulus"];
}
else {
NSLog(#"Error: %#", error);
}
}];
[task resume];
Assuming, this data comes as type NSData, you can do the following:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&myError];
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[#"modulus"];
The Data will be available in the five variables:
errorCode
errorMessage
guid
exponent
modulus
Use + JSONObjectWithData:options:error: to create a NSDictionary of the JSON.
Then access the elements in the usual manner of accessing dictionary items.
Answer by Christopher Mäuer using the literal syntax:
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&error];
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[#"modulus"];
}
else {
NSLog(#"Error: %#", error);
}
Updated for new question code:
Here is sample code, I have re-constructed the data received from the log out put in the question:
NSString *responseBody = #"{\"error_code\":0,\"error_message\":\"\",\"exponent\":\"010001\",\"guid\":\"855fd04f-0016-1805-a3be-84dbef17ffd6\",\"modulus\":\"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5\",\"tran_id\":\"cb2e8149-4961-458a-a6b2-7443bdb01509\"}";
NSData *data = [responseBody dataUsingEncoding:NSUTF8StringEncoding];
// The above was just to get `data` setup.
// The only function of the following two statements is to print the data as a string.
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
//
// NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"res: \n%#", res);
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"];
NSString *modulus = res[#"modulus"];
NSLog(#"errorCode: %#\nerrorMessage: %#\nguid: %#\nexponent: %#\nmodulus: %#", errorCode, errorMessage, guid, exponent, modulus);
}
else {
NSLog(#"Error: %#", error);
}
Output:
Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}
res:
{
"error_code" = 0;
"error_message" = "";
exponent = 010001;
guid = "855fd04f-0016-1805-a3be-84dbef17ffd6";
modulus = C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5;
"tran_id" = "cb2e8149-4961-458a-a6b2-7443bdb01509";
}
errorCode: 0
errorMessage:
guid: 855fd04f-0016-1805-a3be-84dbef17ffd6
exponent: 010001
modulus: C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5
I suggest you replacing the following two lines:
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
With the two code lines I provide:
NSError *error;
NSDictionary* responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
or with the following:
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
So now you have a NSDictionary, which is responseData, so now we can decode your JSON response as follows (I will put the whole code as follows):
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
NSString *guid = [responseData valueForKey:#"guid"];
NSString *exponent = [responseData valueForKey:#"exponent"];
NSString *modulus = [responseData valueForKey:#"modulus"];
NSLog(#"Decoded Response :\n guide : %#,\n exponent : %#,\n modulus : %#", guid, exponent, modulus);
So your whole code which you have pasted above in your Question will look like following:
NSString *temp2 = [NSString stringWithFormat:#"{\n \"partner_key\": \"%#\",\n \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n \"payment_account_id\": \"%#\",\n \"card_number\": \"%#\",\n \"card_exp_date\": \"%#\",\n \"amount\": \"%#\",\n \"memo\": \"%#\",\n \"recipient\": {\n \"email\": \"%#\",\n \"mobile_phone\": \"%#\"\n }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);
NSURL *URL = [NSURL URLWithString:#"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
NSString *guid = [responseData valueForKey:#"guid"];
NSString *exponent = [responseData valueForKey:#"exponent"];
NSString *modulus = [responseData valueForKey:#"modulus"];
NSLog(#"Decoded Response :\n guide : %#,\n exponent : %#,\n modulus : %#", guid, exponent, modulus);
}];
[task resume];
Well, you didn't say anything about how you got the data back, like if you already have it in a NSString or still in NSData, so I'm going to assume you have it in NSData.
NSData *json <- somehow I magically got jSON data into this
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:&error];
NSString guid = [NSString stringWithString:jsonDict[#"guid"];
NSString exponent = [NSString stringWithString:jsonDict[#"exponent"];
NSString modulus = [NSString stringWithString:jsonDict[#"modulus"];
Related
In My code I want to convert NSData to NSDictionary but it returns nil I don't know what mistake I made,I Used NSJSONSerialization for convert data to dictionary, The NSData was received from server response.
Here I show my Full code what I am trying.
-(void)SendPushNotification:(NSString*)getUrl :(NSMutableDictionary *)getData withCompletionBlock:(void(^)(NSDictionary *))completionBlock
{
NSError *error;
NSLog(#"dict val: %#",getData);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:getData options:NSJSONWritingPrettyPrinted error:&error];// Pass 0 if you don't care about the readability of the generated string
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLengthas = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:getUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSString *chkRegDevice= [[NSUserDefaults standardUserDefaults] stringForKey:#"bearer"];
NSString *strfds=[NSString stringWithFormat:#"bearer %#",chkRegDevice];
[request setHTTPMethod:#"POST"];
[request setValue:postLengthas forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:strfds forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
if(error)
{
NSLog(#"%#", [error localizedDescription]);
completionBlock(nil);
}else{
NSError *jsonError;
NSString *clientDetail = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"clientDetail: %#", clientDetail);
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"json %#",json);
if (![clientDetail isEqualToString:#"Object reference not set to an instance of an object."]) {
if (completionBlock) {
completionBlock(json);
}
}
else
{
completionBlock(nil);
}
}
}];
[taskk resume];
}
Here the following response I get to convert NSData to NSString.
"{\"multicast_id\":8856529321585625357,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1534479035021563%1dbdaa031dbdaa03\"}]}"
Pass NSData object(data) directly to JSONObjectWithData.
Also, to check the error, you can print jsonError.
Try the following code:
NSError* error;
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa
options:kNilOptions
error:&error];
NSLog(#"JSON DICT: %#", json);
Try this.
NSString* str = your string data;
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *decodeString = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
NSDictionary *dict = [self dictionaryWithJsonString:decodeString];
/////////////////////
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
return nil;
}
return dic;
}
Firstly I have two text fields first is login and second is password and one login button. I am using a storyboard and login button connected to another view controller by push segue. This time working in my project, Put username and password in textfield and select login button and print server response in console.
I want to login successfully after move another view and login is failed don't move another view.
My php code
<?php
header('Content-type: application/json');
include('../conn.php');
if($_POST)
{
$loginid = $_POST['loginid'];
$loginpassword = $_POST['loginpassword'];
$schoolid = substr_id($loginid);
$table = tb3($schoolid);//profile
$sql=mysql_query("select * from $table where ID = '".$loginid."' AND PASSWORD = '".$loginpassword."'",$conn);
$row=mysql_fetch_assoc($sql);
if(mysql_num_rows($sql)>0)
{
echo '{"success":1}';
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
My viewcontroller code
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
}
}
This line is wrong
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
you are additionally added the & in your params ,this is not in loginpassword=%#& , you need to call like loginpassword=%# remove and send the request
use like
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",_user_id.text,_password.text, nil];
The problem is you are not serlize your JSON
so remove this line in your NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
and I follow your Answer
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
}
Ankur kumawat I tried your coding and Brother #Anbu.karthik answer in iOS 9.I got few warnings.First I post Anbu.Karthik brother answer.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",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];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
Above is brother Anbu.Karthik answer.I tried that and it shows me the warnings.
Warnings are
'sendSynchronousRequest:returningResponse:error:' is deprecated: first
deprecated in iOS 9.0 - Use [NSURLSession
dataTaskWithRequest:completionHandler:] (see NSURLSession.h
Then
Implicit conversion loses integer precision: 'long _Nullable' to 'int'
As I get warning I want to remove warning and
I must use
NSURLSession with dataTask because sendSynchronousRequest:returningResponse:error:' is deprecated in iOS 9.0
Then I modified the code.
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//create the Method "GET" or "POST"
[urlRequest setHTTPMethod:#"POST"];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//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) {
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];
The printed result is
The response is - {
success = 1;
}
And
Login SUCCESS
Now above my code works perfectly:-)
Try this code in view Controller file:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSLog(#"%#",dict);
if (dict)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
}
output: 1 // successfully
or
0 // Unsccssfully
NSString *msg = [NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]];
Replace your code with this :
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
Dictionary *dictResponce = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (dictResponce)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
if (status == "1"){
//Push to home view controller
[self performSegueWithIdentifier:#"Home_page" sender:self];
}
else{
NSLog([NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]]);
}
}
else{
NSLog(#"faield to connect");
}
}
}
I am having problem in using the Microsoft Emotion API i have read the documentation but not able to use it. Whenever i use the below code it gives Bad body JSON parsing error. I am not able to detect whats the problem in code.
i have created a method
- (IBAction)clickToGenerateEmotion:(id)sender
NSString* path = #"https://api.projectoxford.ai/emotion/v1.0/recognize";
NSArray* array = #[
#"entities=true",
];
NSString* string = [array componentsJoinedByString:#"&"];
path = [path stringByAppendingFormat:#"?%#", string];
NSLog(#"%#", path);
UIImage *yourImage= _image;
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
[_request setHTTPMethod:#"POST"];
[_request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[_request setValue:#"9b118d1587ce40899598b48a6c29b51a" forHTTPHeaderField:#"Ocp-Apim-Subscription-Key"];
NSDictionary *params = #{#"\"url\"" : #"\"http://engineering.unl.edu/images/staff/Kayla_Person-small.jpg\""};
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
}
NSString *requestParams = [pairs componentsJoinedByString:#"&"];
[_request setHTTPBody:imageData];
NSURLResponse *response = nil;
NSError *error = nil;
NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
NSLog(#"responseData = %#", [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding]);
if (nil != error)
{
NSLog(#"Error: %#", error);
}
else
{
NSError* error = nil;
NSMutableDictionary* json = nil;
NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
NSLog(#"%#", dataString);
if (nil != _connectionData)
{
json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
}
if (error || !json)
{
NSLog(#"Could not parse loaded json with error:%#", error);
}
NSLog(#"%#", json);
_connectionData = nil;
}
`
Thanks in advance!!!
And it says use [NSURLSession sharedsession] dataTaskwithRequest:request completionHandler:]
So here my code:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
I changed above code to like this:
NSData *returnData = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:nil];
I got 2 warning:
Null passed to a callee that requirs a non-null argument
Incomplete pointer type initializing 'NSData' with a expression of type 'NSURLSession'
Help me out.Please do explain me with code that will helpfull to understand. I am new to ios
My actual code:
-(void)getdata {
NSString *userName = #“user#yahoo”;
NSString *password = #“passr”;
NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://api.eaxmpleurl/files";
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]
dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// Use the data here
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError * error1;
self->arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = jsonResults[#"dark”];
[titleArray addObject:[NSString stringWithFormat:#" Dark(%#)”, dictOriginal[#"count"]]];
NSDictionary *dictOriginal2 = jsonResults[#"opey”];
[titleArray addObject:[NSString stringWithFormat:#" Opey(%#)”, dictOriginal2[#"count"]]];
NSDictionary *dictOriginal3 = jsonResults[#"pef”];
[titleArray addObject:[NSString stringWithFormat:#" Pef(%#)”, dictOriginal3[#"count"]]];
NSDictionary *dictOriginal4 = jsonResults[#"sdf”];
[titleArray addObject:[NSString stringWithFormat:#" Sdf(%#)”, dictOriginal4[#"count"]]];
NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];
NSLog(#"str: %#", titleArray);
for (NSDictionary *dict in arrayFiles) {
NSMutableArray *arr = [NSMutableArray array];
NSArray *a = dict[#"files"];
for(int i=0; i < a.count; i ++) {
NSString *strName = [NSString stringWithFormat:#"%#",[[dict[#"files"] objectAtIndex:i] valueForKey:#"name"]];
// NSLog(#"str: %#", strName);
[arr addObject:strName];
}
[arrayPDFName addObject:arr];
}
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:#"SampleData.plist"];
NSString *error2;
data = [ NSPropertyListSerialization dataWithPropertyList:jsonResults format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if(data ) {
if ([data writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
}
NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
#pragma unused (stringsDictionary)
#pragma unused (error1)
#pragma unused (str)
}];
// Starting the task
[dataTask resume];
}
You need to use that method like:
// Creating a data task
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]
dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// Use the data here
}];
// Starting the task
[dataTask resume];
Please check dataTaskWithRequest:completionHandler: for more detailed information.
Good afternoon,
I'm trying to store the response from a JSON output because I want to show in a "ProfileViewController" the stats of the users and I'm trying to use the following function in order to store the information.
At the moment the output is fine, because the data is OK depending on the users, but now I have to store each one of the stats in a "variable" for each of the stats (I have 3) but when I run the code it didn't show my NSLog for Stars, Followers and Pictures...
Can you help me with that? The response is fine, now I just want to store each one of the stats in a single variable. How can I do that? What's wrong in my code?
ProfileViewController -> fetchJson:
-(void)fetchJson {
NSString *usersPassword = [SSKeychain passwordForService:#"login" account:#"account"];
NSString *post =[[NSString alloc] initWithFormat:#"usersPassword=%#",usersPassword];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://website.com/profile.php"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%ld",(long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* stars = [jsonObject objectForKey:#"stars"];
NSLog(#"Stars ==> %#", stars);
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* followers = [jsonObject2 objectForKey:#"followers"];
NSLog(#"Followers ==> %#", followers);
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* photos = [jsonObject3 objectForKey:#"photos"];
NSLog(#"Pictures ==> %#", photos);
}
}
}
}
JSON output:
{"success":1,"stars":50,"photos":50,"followers":50}
Thanks in advance.
jsonData already contains the parsed response and as you have successfully retrieved success value from it as follows,
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%ld",(long)success);
You can retrieve other value as follows,
[[jsonData objectForKey:#"stars"] integerValue]
and so on.
You didn't have to create foundation object by using following method
NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
and following block of code is unnecessary,
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* stars = [jsonObject objectForKey:#"stars"]
NSLog(#"Stars ==> %#", stars);
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* followers = [jsonObject2 objectForKey:#"followers"];
NSLog(#"Followers ==> %#", followers);
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* photos = [jsonObject3 objectForKey:#"photos"];
NSLog(#"Pictures ==> %#", photos);
}
_jsonArray = [NSJSONSerialization JSONObjectWithData:myNSData options:kNilOptions error:&error];
NSDictionary * jsonObject = (NSDictionary *)_jsonArray;
and then check dictionary object.