hi I am trying to send a request to server and I am trying to set the value of three labels with reply of the server
my code:-
NSString *post = [NSString stringWithFormat:#"phone=%#",self.tmvp];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://test.kre8tives.com/barebon/customer_dataapi.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
static NSURLSession* sharedSessionMainQueue = nil;
if(!sharedSessionMainQueue){
sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
}
[[sharedSessionMainQueue dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSDictionary *temp=jsonDict;
NSLog(#"Req cust:%#",requestReply);
NSLog(#"requestReply cust: %#", jsonDict);
self.names=[temp valueForKey:#"customer_name"];
[self.namel setText:[NSString stringWithFormat:#"%#", self.names]];
// _namel.text = [NSString stringWithFormat:#"%#",self.names];
self.emails=[temp valueForKey:#"email"];
_emaill.text=[NSString stringWithFormat:#"%#",self.emails];
self.dobs=[temp valueForKey:#"dob"];
_dobl.text=[NSString stringWithFormat:#"%#",self.dobs];
self.iname=[temp valueForKey:#"image"];
NSLog(#"%#",self.names);
NSLog(#"%#",self.emails);
NSLog(#"**%#",self.dobs);
NSLog(#"requestReply: %#", requestReply);
NSLog(#"imagename:%#",self.iname);
[self imagedl];
NSString *valueToSave =[jsonDict valueForKey:#"customer_id"];
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:#"custid"];
[[NSUserDefaults standardUserDefaults] synchronize];
}] resume];
first I am sending phone number and I get name, email,dob etc from server
this is my log
2017-06-09 14:14:50.006 MenuBar[4127:203694] (
Akshay
)
2017-06-09 14:14:51.503 MenuBar[4127:203694] (
"akshay1318a#yahoo.com"
)
2017-06-09 14:14:51.503 MenuBar[4127:203694] **(
"18-01-1995"
)
2017-06-09 14:14:53.041 MenuBar[4127:203694] requestReply: [{"customer_id":"111","customer_name":"Akshay","email":"akshay1318a#yahoo.com","phone":"9047038606","dob":"18-01-1995","image":"+919047038606cache.png","level":"0","created_date":"2017-06-07 11:12:55","current_store":"0"}]
2017-06-09 14:14:53.042 MenuBar[4127:203694] imagename:(
"+919047038606cache.png"
)
2017-06-09 14:14:53.041 MenuBar[4127:203694] requestReply: [{"customer_id":"111","customer_name":"Akshay","email":"akshay1318a#yahoo.com","phone":"9047038606","dob":"18-01-1995","image":"+919047038606cache.png","level":"0","created_date":"2017-06-07 11:12:55","current_store":"0"}]
this Is my reply but why am I getting a bracket here??? because of that the label shows only bracket!!!in server too there is no bracket added I double checked it!!
Related
I'm having trouble with my tableView. In practice, I have two tableViews and when I click on an element of the first tableView, I open the second tableView where I'm going to fetch a JSON (which works correctly because the dictionary contains all the right data). But the problem is that these downloaded data are not immediately displayed in the tableView, which remains empty. If I go back to the first tableView and reopen the same cell, the data magically appear.
So I thought it might be a problem because if I'm wrong the JSON requests are asynchronous, so I wrote the method:
dispatch_async (dispatch_get_main_queue (), ^ {
[self.tableView reloadData];
});
But it does not work anyway. Do you have any idea? This is my code:
self.arrayPM = [[NSMutableArray alloc] init];
if(![NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:#"dictpm"]]){
NSString *username = #"user";
NSString *password = #"pwd";
NSString *post = [NSString stringWithFormat:#"upmon_id=%#&user=%#&pwd=%#", pm_id, username, password];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu" , (unsigned long)[postData length]];
NSURL *url = [NSURL URLWithString:#"urlblabla"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
return;
}
if((long)[(NSHTTPURLResponse *)response statusCode] == 200) {
NSError *jsonError;
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonResponse];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"dictpm"];
}
}];
[task resume];
}
else {
jsonResponse = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:#"dictpm"]];
for (int i = 0; i < [jsonResponse count]; i++)
{
PianoMonitoraggio *newPM = [[PianoMonitoraggio alloc] init];
bla bla bla, code
[self.arrayPM addObject:newPM];
}
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.arrayPM];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"arrayPM"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self.tableView reloadData];
}
I am trying to create a login screen where one has to enter his UserName and Password. On clicking the login button I am parsing the details to the server. Here's the code
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",[_userNameText text],[_passwordText text]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu" , (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://*******/*****/******/userLogin.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"sample data"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",_requestReply);
}] resume];
So far the code works just as intended. Now I want to check if the "requestReply" that is returned from the server has the value "success" for it's "status" key. So I tried to print it's value with the following code.
_responseData = _requestReply;
NSLog(#"%#" , _responseData[#"status"]);
And here's the console output
2016-10-21 06:44:03.424 QuizApp2[65724:1287972] (null)
2016-10-21 06:44:03.501 QuizApp2[65724:1288003] {"status":"success","message":"Welcome admin","code":true}
I am not sure, but I felt that the last line of the code is executing before the parsing happens. Can someone please highlight how the control flows here? Or is there anything wrong with my code?
I didn't see any code about parse data. Do you mean this line
_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
If the userLogin.php returns a JSON data, just do this:
[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
NSError *err = nil;
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
if (err) {
NSLog(#"%#", err);
}
else {
NSLog(#"%#", jsonData[#"status"]);
}
}] resume];
I'm trying to post new data to a ws but im geting error each time
I need to
1-pass a username and password each time
2-code the data with AES256 WITH THE API KEY
Code:
- (IBAction)AddTicket:(id)sender {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *URL = [[NSURL alloc] initWithString:#"http://dev.enano-tech.com/api/Ticket"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"1",#"idProject",#"1",#"idTicketType",#"nameo",#"name",#"nameo",#"description", #"1",#"idStatus",#"2016-06-23 15:20:49",#"creationDateTime", nil];
NSData *dataToPost = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSData *final =[dataToPost AES256EncryptWithKey:#"02b6e206868660a0d59d2e51a11fdcd6"];
//
NSLog(#"postData1e == %#",final);
NSLog(#"final %#",dataToPost);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request addValue:#"CURLAUTH_BASIC" forHTTPHeaderField:#"CURLOPT_HTTPAUTH"];
[request addValue:#"Basic YWRtaW46YWRtaW5hZG1pbg==" forHTTPHeaderField:#"authorization"];
[request addValue:#"admin:adminadmin" forHTTPHeaderField:#"CURLOPT_USERPWD"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_RETURNTRANSFER"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_SSL_VERIFYPEER"];
[request addValue:#"POST" forHTTPHeaderField:#"CURLOPT_CUSTOMREQUES"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_POST"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_POSTFIELDS"];
[request setHTTPBody:final];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *str = [[NSString alloc]initWithData:final encoding:NSUTF8StringEncoding];
NSLog(#"data %#",data);
NSLog(#"respoce %#",response);
NSLog(#"result == %#",result);
}];
[postDataTask resume];
}
Response:
2016-08-02 15:06:47.768 Projector[3936:1619429] result == {"error":"invalid API query", "message":"'data' is not correctly encoded for method POST. Request for correct API KEY"}
this is the documentation of api:
enter image description here
Your webserver is missing "data" from the website. To fix it, you'll need to add that field to your form or find the correct field name (case sensitive)
Hi i am very new for ios and in my app i have used ASIFormDataRequest earlier days for integrating the services
now i have changed format and i am using NSURLSession instead of ASIFormDataRequest
But when i request change password to server using ASIFormDataRequest success response is coming from server but when i use NSURLSession failed response coming from server please help what is wrong
NSURlsession:-
def = [NSUserDefaults standardUserDefaults];
NSString *myString = [def stringForKey:#"AccesToken"];
NSString *AccessToken = [NSString stringWithFormat:#"Bearer %#",myString];
NSString *Finalstr = [NSString stringWithFormat: #"MedicaidId=%#&OldPassword=%#&NewPassword=%#&ConfirmPassword%#", medicaId,self.CurPwdTxt.text,self.NewPwdTxt.text,self.ConfPwdTxt.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:mainurl,BaseURL]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[Finalstr dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:AccessToken forHTTPHeaderField:#"Authorization"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"responseobject is %#",responseObject);
}else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
NSLog(#"responseobject is%#",responseObject);
} else {
NSLog(#"responseobject is %#",responseObject);
}
//if response was text/html, you might convert it to a string like so:
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}
}];
[task resume];
}
ASIFormDataRequest:-
NSString *urlStr = [NSString stringWithFormat:#"myurl",BaseURL];
NSLog(#"urlStr --->>> %#",urlStr);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
def = [NSUserDefaults standardUserDefaults];
NSString *myString = [def stringForKey:#"AccesToken"];
NSString *str = [NSString stringWithFormat:#"Bearer %#",myString];
NSLog(#"token is %#",str);
[request setPostValue:medicaId forKey:#"MedicaidId"];
[request setPostValue:self.CurPwdTxt.text forKey:#"OldPassword"];
[request setPostValue:self.NewPwdTxt.text forKey:#"NewPassword"];
[request setPostValue:self.ConfPwdTxt.text forKey:#"ConfirmPassword"];
[request addRequestHeader:#"Authorization" value:str];
[request setDelegate:self];
[request startAsynchronous];
You are sending different requests there. In the 'new' code, you are constructing the POST data like this:
#"MedicaidId=%#&OldPassword=%#&NewPassword=%#&ConfirmPassword%#"
which looks like GET-parameters more than form-encoding (which you use on the 'old' request).
Tracking your request and checking out the actual request using something like Wireshark might help you out to spot the problem yourself next time.
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.